使用 Selenium 在特定元素之后通过 CSS 选择器查找元素
Find element by CSS selector AFTER certain element with Selenium
我正在寻找文本“Interesting”,这是 class b
在 h1.important
之后的第一次出现。
我将如何在 Selenium 中做到这一点?
<div class="a">
<div class="b">Not interesting</div>
</div>
<div class="title">
<h1 class="important">Title</h1>
</div>
<div class="a">
<div class="b">Interesting</div>
</div>
有没有办法使用花哨的选择器或 xpath 找到“有趣的”?
这也将匹配第一个元素:driver.find_elements_by_css_selector(".b").text
driver.find_elements_by_css_selector(".b")
这将在 Python-Selenium 绑定 中 return list
。所以你不能对它做 .text
。
改为尝试使用 driver.find_element
,如下所示:
driver.find_element_by_css_selector("div.title+div>.b").text
如果您想使用 xpath,试试这个:
driver.find_element_by_xpath("//div[@class='title']/following-sibling::div/div").text
请注意,CSS_SELECTOR
在 Selenium 自动化中优于 xpath
。
这个 XPath
//h1[@class='important']/../following-sibling::*//*[@class='b']
应该在您询问 h1.important
节点后给您下一个 b
class 事件
这个 xpath 应该可以工作
(//h1[@class="important"]/following::*[@class='b'])[1]
我正在寻找文本“Interesting”,这是 class b
在 h1.important
之后的第一次出现。
我将如何在 Selenium 中做到这一点?
<div class="a">
<div class="b">Not interesting</div>
</div>
<div class="title">
<h1 class="important">Title</h1>
</div>
<div class="a">
<div class="b">Interesting</div>
</div>
有没有办法使用花哨的选择器或 xpath 找到“有趣的”?
这也将匹配第一个元素:driver.find_elements_by_css_selector(".b").text
driver.find_elements_by_css_selector(".b")
这将在 Python-Selenium 绑定 中 return list
。所以你不能对它做 .text
。
改为尝试使用 driver.find_element
,如下所示:
driver.find_element_by_css_selector("div.title+div>.b").text
如果您想使用 xpath,试试这个:
driver.find_element_by_xpath("//div[@class='title']/following-sibling::div/div").text
请注意,CSS_SELECTOR
在 Selenium 自动化中优于 xpath
。
这个 XPath
//h1[@class='important']/../following-sibling::*//*[@class='b']
应该在您询问 h1.important
节点后给您下一个 b
class 事件
这个 xpath 应该可以工作
(//h1[@class="important"]/following::*[@class='b'])[1]