【问题标题】:Contains text in Selenium Python包含 Selenium Python 中的文本
【发布时间】:2019-05-03 08:14:31
【问题描述】:

我正在尝试捕获一个错误,该错误将重新启动我的程序并更改代理,但我无法捕获该错误,因为它像这样存储并且类是动态命名的:

<p class="g4Vm4">By signing up, you agree to our <a target="_blank" href="https://help.instagram.com/581066165581870">Terms</a> . Learn how we collect, use and share your data in our <a target="_blank" href="https://help.instagram.com/519522125107875">Data Policy</a> and how we use cookies and similar technology in our <a target="_blank" href="/legal/cookies/">Cookies Policy</a> .</p>

所以我试图通过这个函数捕获 xpath,但我无法这样做。

def has_error(browser):
        try:            #/*[contains(text(), 'technology')]/html/body/span/section/main/div/article/div/div[1]/div/form/p"
            browser.find_element_by_xpath("/html/body//*[contains(text(),'technology')]")
            return False
        except: return True
        if not has_error(browser):
            print('Error found! , aborted!')
            browser.quit()
            os.execv(sys.executable, ['python'] + sys.argv)

【问题讨论】:

    标签: python-3.x selenium selenium-webdriver automation


    【解决方案1】:

    要处理动态元素,请使用WebDriverwait 并关注Xpath Startegy。

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions
    
    
    element=WebDriverWait(driver,30).until(expected_conditions.element_to_be_clickable((By.XPATH,'//p[contains(.,"technology")]')))
    print(element.text)
    

    【讨论】:

      【解决方案2】:

      您可以检查网页的来源是否包含特殊文本。

      if 'By signing up, you agree to our ' in browser.page_source:
          pass
          # TODO Exception
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-02
        • 1970-01-01
        • 1970-01-01
        • 2020-10-14
        • 1970-01-01
        • 2012-09-01
        相关资源
        最近更新 更多