简体   繁体   English

使用包含在 Selenium webdriver XPATH 中查找文本

[英]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.我正在工作 Python 的 30 天 - 第 16 天 - 使用 Selenium 和 Python 在受密码保护的应用程序后面进行抓取和自动化。

However, I found that using XPATH to find the button 'Follow' in Instagram is not working.但是,我发现使用 XPATH 在 Instagram 中查找“关注”按钮不起作用。

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.您不能在 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 .这会起作用:注意:您将Follow视为follow The text is Follow , not follow DOM文本是Follow ,不是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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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