简体   繁体   中英

How do I click on the dynamic Twitter follow button with selenium and python?

I am trying to click on twitter's follow button, but it is dynamic and has attributes, which I don't find much about on the selenium documentation.This is the html of the button:

代码截图

This is currently my follow function:

    def follow(driver, username):
        driver.get('https://twitter.com/' + username)
        wait = WebDriverWait(driver, 10)
        follow = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'follow-button')))
        follow.click()

Try the following Xpath to click on the Follow

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

OR

wait = WebDriverWait(driver, 10)
follow = wait.until(EC.element_to_be_clickable((By.XPATH, '//span[contains(.,"Follow")]')))
follow.click()

You are getting TabError: inconsistent use of tabs and spaces in indentation because follow.click() was not inline in your initial code.Try now.

def follow(driver, username):
    driver.get('https://twitter.com/' + username)
    wait = WebDriverWait(driver, 10)
    follow = wait.until(EC.element_to_be_clickable((By.XPATH, '//span[text()="Follow"]')))
    follow.click()

try this xpath

(//span[text()='Follow']/ancestor::div[@role='button'])[1]

Index [1] will always pick the first Follow button, in case if there are multiple Follow buttons.

You could try a generic XPath selector that only looks for the presence of 'Follow' text and does not care about the enclosing tag:

//*[contains(text(), 'Follow')]

Or

//*[text()='Follow']

If there are multiple instances of this button, you can try:

Driver.FindElement(By.XPath("//*[text()='Follow']")[0].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