简体   繁体   中英

Finding text in Selenium webdriver XPATH using contains

I am working on 30 Days of Python - Day 16 - Scrape & Automate behind Password Protected Apps with Selenium & Python.

However, I found that using XPATH to find the button 'Follow' in Instagram is not working.

def click_to_follow(browser):
   my_follow_btn_xpath = '//*[contains(text()='follow')]'
    follow_btn_els = browser.find_elements(By.XPATH, my_follow_btn_xpath)
    for btn in follow_btn_els:
        try:
            btn.click()
        except:
            pass


new_user = 'ted'
new_user_url = f'http://www.instagram.com/{new_user}/'
browser.get(new_user_url)

click_to_follow(browser)

The above is the code, but it shows that I had an invalid syntax.

 my_follow_btn_xpath = '//*[contains(text()='follow')]'
                                                ^^^^^^
SyntaxError: invalid syntax

Could any one help with this? I have search for similar posts but I still can't work it out.

You can't use single quotes inside your xpath.

Change this:

my_follow_btn_xpath = '//*[contains(text()='follow')]'

to this:

my_follow_btn_xpath = '//*[contains(text()="follow")]'

This would work: Note: You took Follow as follow . The text is Follow , not follow DOM

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//div[text()='Follow']"))).click()

This would be the specific element that you want:

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//h1//parent::div//div[text()='Follow']"))).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