代码之家  ›  专栏  ›  技术社区  ›  Greta

硒无法获取元素。使用python和web驱动程序时显示文本

  •  0
  • Greta  · 技术社区  · 3 年前
    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    chrome_driver_path = "/Users/greta/Development/chromedriver"
    driver = webdriver.Chrome(executable_path=chrome_driver_path)
    
    driver.get("https://en.wikipedia.org/wiki/Main_Page")
    
    articles = driver.find_element(By.XPATH, "/html/body/div[3]/div[3]/div[5]/div[1]/div[1]/div/div[3]/a[1]")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/div[3]/div[5]/div[1]/div[1]/div/div[3]/a[1]"))).click()
    try:
        number_of_articles = articles.get_attribute("textContent")
        print(number_of_articles)
    except:
        print("Unable to find")
    finally:
        driver.quit()
    

    我正在用Python学习Selenium。以上是我的代码。我想在维基百科中检索这个带圆圈的元素,因为我们可以看到它是一个锚标签 <a> 这在一个小时之内 <div> 其id为“articlecount”。我已经试过了。CSS_选择器不起作用,所以我使用XPATH,如代码所示。但它仍然不起作用。

    然后我发现如果我打印 articles 变量本身,代码不会引发错误。然而,一旦我打印 articles.text articles.get_attribute("textContent") ,错误仍然发生。

    如果有人能帮我,那就太好了。提前谢谢。

    enter image description here

    enter image description here

    1 回复  |  直到 3 年前
        1
  •  0
  •   Manish Dash    3 年前

    你有一只小虫子。在这一行中,您在找到元素后单击该元素,这会导致页面更改,并且您无法找到文章计数。

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/div[3]/div[5]/div[1]/div[1]/div/div[3]/a[1]"))).click()
    

    只需移除 click() 它会起作用的