Python + Selenium WebDriver-如果同级包含字符串,则获取div值 [英] Python + Selenium WebDriver - Get div value if sibling contains string
问题描述
我正在尝试使用Python/Selenium从网页中的div获取值,在该类中,类名是重复的,但包含唯一的字符串,例如下面的结构.
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>
如何仅从包含"col_Num = 1"的div中获取"Col_Val"的值? (应返回值5.00并将其保存到变量中)
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)
我目前试图将Selenium IDE(从我自己过去的问题中获得的代码)转换为Python的解决方案如下,但在CSS选择器中无效,因为"contains"无效,所以我相信我必须使用Xpath但不知道如何.
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
推荐答案
following-sibling
轴在这里会有所帮助:
following-sibling
axis would help here:
following-sibling
轴表示所有具有相同节点的节点 父作为上下文节点,并出现在 源文档.
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"]
这篇关于Python + Selenium WebDriver-如果同级包含字符串,则获取div值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!