使用 aria-label 通过 Python3 和 Selenium 定位并单击元素

问题描述 投票:0回答:3

我想分别单击或更多,展开“随时”按钮。我尝试通过 class_name 和 xpath 来定位该元素。问题是所有三个“选项”的类和 xpath 都是相同的。因此,我想使用 aria-label 选择并单击或展开该元素。我找到了一些建议,但对我来说不起作用。最重要的是,我尝试在 python 3 中这样做。我也尝试过:

driver.find_element_by_xpath(""" //div*[@aria-label='Any Time'] """).click()

但它不起作用。

有人可以帮助我吗?非常感谢!

<div class="hdtb-mn-hd" aria-haspopup="true" role="button" tabindex="0" aria-label="Any country"><div class="mn-hd-txt">Any country</div><span class="mn-dwn-arw"></span></div>
<div class="hdtb-mn-hd" aria-haspopup="true" role="button" tabindex="0" aria-label="Any time"><div class="mn-hd-txt">Any time</div><span class="mn-dwn-arw"></span></div>
<div class="hdtb-mn-hd" aria-haspopup="true" role="button" tabindex="0" aria-label="All results"><div class="mn-hd-txt">All results</div><span class="mn-dwn-arw"></span></div>

python selenium xpath
3个回答
32
投票

所以,过去几天我一直在努力解决这个问题,事实证明这是一个非常令人头痛的问题。 aria-label 基本上是唯一可靠的属性,xpath 解决方案对我不起作用。

一时兴起,我尝试使用:

driver.find_elements_by_css_selector("[aria-label=XXXX]")

其中 XXXX 是我在单引号中搜索的咏叹调标签(例如“[aria-label='More']”)。效果非常好。

说了这么多,请尝试使用 css 选择器。它就可以了。


17
投票

使用

aria-label
属性,您可以尝试以下
xpath
:

driver.find_element_by_xpath("//div[@aria-label='Any time']/div[@class='mn-hd-txt' and text()='Any time']");

driver.find_element_by_xpath("//div[@aria-label='Any time']/div[@class='mn-hd-txt'][text()='Any time']");

如果使用

aria-label
属性不是强制性要求,您可以使用以下内容:

driver.find_element_by_xpath("//div[@class='hdtb-mn-hd']/div[@class='mn-hd-txt' and text()='Any time']");

driver.find_element_by_xpath("//div[@class='hdtb-mn-hd']/div[@class='mn-hd-txt'][text()='Any time']");

0
投票
import { By } from "selenium-webdriver";    

await driver.findElements(By.css("svg[aria-label='Hello']"));
© www.soinside.com 2019 - 2024. All rights reserved.