请有人告诉我是否可以在 Xpath 查询中引用 2 个类?请参阅下文。运行此脚本时出现脚本错误。我正在通过 Selenium 使用 python 2.7。
list_ppl_link = driver.find_element_by_xpath('//div[@class="pro-tease"]//div[@class="pro-tease even"]')
Run Code Online (Sandbox Code Playgroud)
您应该能够选择具有多个类的元素,如下所示:
//div[contains(@class, "pro-tease") and contains(@class, "even")]
Run Code Online (Sandbox Code Playgroud)
这将选择同时具有和类的div
s ,例如 pro-tease
even
<div class="pro-tease something even">...</div>
<div class="irrelevant pro-tease foo even">...</div>
Run Code Online (Sandbox Code Playgroud)
但是,它不会选择仅具有两个指定类之一的 div。如果要选择具有一个类或另一个类的元素,请尝试以下操作:
//div[contains(@class, "pro-tease") or contains(@class, "even")]
Run Code Online (Sandbox Code Playgroud)
现在,如果你有四个 div:
<div class="pro-tease irrelevant">...</div>
<div class="even irrelevant">...</div>
<div class="not specified">...</div>
<div class="pro-tease even">...</div>
将选择 1、2、4,因为它们都包含pro-tease
或 even
。
到目前为止,您可能已经注意到contains()
它完全按照它所说的去做:检查类名是否包含指定的参数。因此,如果你连接两个contains()
带and
,你基本上是说“给我包含这个类的元素,并还这一个”,而与or
它更像是“给我有元素要么这个类,或者这个类”。
顺便说一下,您可以通过搜索元素 (Ctrl + F) 在 Chrome 开发人员模式 (Ctrl+Shift+I) 中测试您的查询。如果您的查询在浏览器中不起作用,那么它在其他地方也可能不起作用。
归档时间: |
|
查看次数: |
6713 次 |
最近记录: |