Using aria-label to locate and click an element with Python3 and Selenium

风流意气都作罢 提交于 2021-01-20 04:17:55

问题


I want to click or more respectively, expand the "Any time" button. I've tried to locate the element by class_name and xpath. The problem is that the class and xpath are the same for all three 'options'. So, I would like to select and click or expand on that element by using the aria-label. 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:

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>

回答1:


Using the aria-label property you can try the following 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:

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']");



回答2:


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.

On a whim, I tried using:

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

where XXXX was the aria labels that I was searching for. Worked like a charm.

All this to say, try using the css selector. It just works.



来源:https://stackoverflow.com/questions/46669850/using-aria-label-to-locate-and-click-an-element-with-python3-and-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!