[英]Using aria-label to locate and click an element with Python3 and Selenium
I want to click or more respectively, expand the "Any time" button. 我要分别单击或更多,展开“任何时间”按钮。 I've tried to locate the element by class_name and xpath.
我试图通过class_name和xpath来定位元素。 The problem is that the class and xpath are the same for all three 'options'.
问题在于,所有三个“选项”的类和xpath都相同。 So, I would like to select and click or expand on that element by using the aria-label.
因此,我想使用aria标签选择并单击或扩展该元素。 I found a couple of suggestions, but it didn't work for me.
我发现了一些建议,但对我没有用。 Most importantly, I try to do that in python 3. I also tried:
最重要的是,我尝试在python 3中做到这一点。我也尝试过:
driver.find_element_by_xpath(""" //div*[@aria-label='Any Time'] """).click()
but it doesn't work. 但这不起作用。
Could anyone please help me? 谁能帮我吗? Many thanks in advance!
提前谢谢了!
<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>
Using the aria-label
property you can try the following xpath
: 使用
aria-label
属性,您可以尝试以下xpath
:
driver.find_element_by_xpath("//div[@aria-label='Any time']/div[@class='mn-hd-txt' and text()='Any time']");
OR
要么
driver.find_element_by_xpath("//div[@aria-label='Any time']/div[@class='mn-hd-txt'][text()='Any time']");
If using aria-label
property is not a mandatory requirement you can use the following: 如果不是必须使用
aria-label
属性,则可以使用以下命令:
driver.find_element_by_xpath("//div[@class='hdtb-mn-hd']/div[@class='mn-hd-txt' and text()='Any time']");
OR
要么
driver.find_element_by_xpath("//div[@class='hdtb-mn-hd']/div[@class='mn-hd-txt'][text()='Any time']");
So, I was just wrestling with this for the last couple days, and it was proving to be a huge headache. 因此,最近几天我一直在为此苦苦挣扎,事实证明,这令人头疼。 The aria-label was basically the only reliable attribute, and the xpath solution was not working for me.
aria标签基本上是唯一可靠的属性,而xpath解决方案不适用于我。
On a whim, I tried using: 一时兴起,我尝试使用:
driver.find_element_by_css_selector("aria-label=XXXX")
where XXXX was the aria labels that I was searching for. XXXX是我要搜索的aria标签。 Worked like a charm.
像魅力一样工作。
All this to say, try using the css selector. 所有这些,请尝试使用css选择器。 It just works.
它只是工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.