代码之家  ›  专栏  ›  技术社区  ›  Shashi Shankar Singh

使用python selenium用给定的文本标识元素

  •  1
  • Shashi Shankar Singh  · 技术社区  · 7 年前

    我有一个网页下面的元素,我正在努力刮。

    <a href="http://www.mylink/?p=20391">Sup Bonds Result June 26, 2018</a>
    

    下面是我试图使用的代码,但似乎不起作用,尽管值存在。它在最初的几个实例中起作用,但随后没有提供任何结果。

    try:
        element=driver.find_element_by_partial_text('Sup Bonds Result June 26, 2018')
    
    except NoSuchElementException:
        driver.quit()
    

    下面是我收到的错误,我已经使用了time.sleep o允许脚本有时间定位元素。

    selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"Sup Bonds Result June 26, 2018"}
    

    如有任何帮助,我们将不胜感激。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Andersson    7 年前

    尝试应用 ExplicitWait 如下所示:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait as wait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException
    
    try: 
        wait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Sup Bonds Result June 26, 2018")))
    except TimeoutException:
        driver.quit()
    

    还请注意,如果要使用按链接文本(部分链接文本)搜索,则需要完全按照它传递文本 出现在浏览器的页面上 ,但不是页面源中显示的那样。所以如果它看起来像 "SUP BONDS..." 你需要在代码中使用相同的

        2
  •  1
  •   undetected Selenium    7 年前

    你好像很亲近。因为你只是想 定位 ( 不点击 )元素,你需要诱导 网络驱动器 对于 元素的可见性 具体如下:

    try:
        element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.PARTIAL_LINK_TEXT, "Sup Bonds Result June 26, 2018"))).click()
    except TimeoutException:
        driver.quit()
    

    注意 :必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException