简体   繁体   中英

Python Selenium xPath select from div class a rel

<div class='into'>
    <div class="state  " rel="AA" style="width:80px;">AA (1028)</div>
    <div class="state  " rel="BB" style="width:80px;">BB (307)</div>
</div>

I'd like to select one of elements rel="AA" or rel="BB" to click on it, tried several ways. The most usable idea was:

browser.find_element_by_xpath("//div[@class='into']/[text()='AA']").click()

However there is a number after the text what is various.

browser.find_element_by_xpath("//div[@class='into']/[rel='AA']").click()

And this not works.

Use the following xpath

browser.find_element_by_xpath(".//div[@class='into']/div[@rel='CA']").click()

Also can use normalize-space method to omit the spaces in your class name like below -

browser.find_element_by_xpath(".//div[normalize-space(@class)='state'][@rel='AA']").click()

If you want to use your example with text() then you could use either of the following:

browser.find_element_by_xpath("//div[@class='into']/div[contains(text(), 'AA')]").click()

or

browser.find_element_by_xpath("//div[@class='into']/div[starts-with(text(), 'AA')]").click()

otherwise use the answer given by @lauda and use @rel to declare it as an attribute

如果您需要XPath匹配具有rel="AA"rel="BB"属性的元素之一(以防其中之一可能不在页面上),请尝试以下操作:

browser.find_element_by_xpath("//div[@class='into']/div[@rel="AA" or @rel="BB"]").click()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM