如何使用硒和python单击动态Twitter跟随按钮?

时间:2019-09-23 16:50:05

标签: python html selenium

我试图单击twitter的关注按钮,但是它是动态的并且具有属性,我在硒文档中找不到很多。这是按钮的html:

Screenshot of code

这是我目前的关注功能:

    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()

2 个答案:

答案 0 :(得分:0)

尝试以下Xpath单击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()

您之所以得到TabError: inconsistent use of tabs and spaces in indentation,是因为follow.click()不在您的初始代码中内联。请立即尝试。

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()

答案 1 :(得分:0)

尝试这个?xpath

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

如果有多个“跟随”按钮,索引[1]将始终选择第一个“跟随”按钮。