Reputation: 311
I am trying to get a value from a div in a web page using Python/Selenium where class names are repeated but contain unique strings, such as the structure below..
<div class='ClassName'>
<div class="col_Num">1 </div>
<div class="col_Val">5.00 </div>
</div>
<div class='ClassName'>
<div class="col_Num">2 </div>
<div class="col_Val">2.00 </div>
</div>
How do I get the value of 'Col_Val' from only the div that contains "col_Num = 1"? (the value 5.00 should be returned and saved to a variable)
My current attempt at a solution which comes from converting Selenium IDE (code obtained from my own past question) to Python is as below, but doesnt work as 'contains' is not valid in css selector so I beleive I must use Xpath but do not know how.
price = driver.find_element_by_css_selector("div:contains(\"1\")+[class=col_Val]").text
Upvotes: 1
Views: 642
Reputation: 2291
Actually, Contains is a CSS2 function that is not supported in CSS3, but Selenium supports the superset of CSS1, 2, and 3. So, you css selector should work with some modification.
price = driver.find_element_by_css_selector("div:contains('1') + div.col_Val").text
Upvotes: 0
Reputation: 473763
following-sibling
axis would help here:
The
following-sibling
axis indicates all the nodes that have the same parent as the context node and appear after the context node in the source document.
//div[@class = "col_Num" and . = "1 "]/following-sibling::div[@class = "col_Val"]
Upvotes: 3