简体   繁体   中英

How do you select the 2nd instance of a span with a specific text using xpath in python's selenium?

I am working with a webpage that I am trying to web craw through. The webpage has multiple with the text of "Apply Now" and I am trying to figure out how to select a certain "Apply Now". If I run the below code, it does work but it selects the first one. How would I adjust it to get the second, third, tenth, etc instances. I assume somewhere I will need to put a " 2 " but I am not sure where.

Apply_Element = driver.find_element_by_xpath("//span/span[contains(.,'Apply Now')]").click()

Update - HTML (sorry for pictures instead of code; I don't know how to copy out of Chrome without losing all the formatting. You can see the "Apply Now" in both in white)

First Section在此处输入图片说明

Second Section在此处输入图片说明

You may do it using xPath position like this:

(//span[contains(.,'Apply Now')])[position()=2]
(//span[contains(.,'Apply Now')])[2] !-- shorter equivalent

Note: position is selecting nth child of current context. So that following applies:

//span[2] !-- selects all spans, which are 2nd child of their parent node
(//span)[2] !-- selects 2nd span on the page

Quick answer: append [2] at the end of your statement after the final ] and before the "

More detailed answer: Learn the way of the relative path. Right now you can simply use the index, but what if you want to be more specific in your locators? Anticipate that there could be changes and the Apply Now #2 may become Apply Now #3 in the future. If you use xpath syntax which narrows down the area and then specifies the Apply Now text, it becomes more precise. For example

//div[contains(@class, '_ngcontent-ypp')]//span[contains(.,'Apply Now')]

I also recomment using an xpath validator plugin like Try Xpath. It really helps with fine-tuning the madness that is xpath...

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