使用 python 和网络驱动程序时,Selenium 无法获得 element.text
Selenium is unable to get element.text while using python and web driver
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。以上是我的代码。我想在维基百科中检索这个带圆圈的元素,因为我们可以看到它是一个位于 <div>
中的锚标记 <a>
,其 id 为“articlecount”。我试过 By.CSS_SELECTOR 没有用,所以我改用 XPATH,如代码所示。但是还是不行。
然后我发现如果我单独打印 articles
变量,代码不会引发错误。但是,当我打印 articles.text
或 articles.get_attribute("textContent")
时,错误仍然出现。
如果有人能帮助我,那就太好了。提前致谢。
enter image description here
enter image description here
你有一个小错误。这一行,你在找到元素后点击,导致页面发生变化,找不到文章数
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()
即可
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。以上是我的代码。我想在维基百科中检索这个带圆圈的元素,因为我们可以看到它是一个位于 <div>
中的锚标记 <a>
,其 id 为“articlecount”。我试过 By.CSS_SELECTOR 没有用,所以我改用 XPATH,如代码所示。但是还是不行。
然后我发现如果我单独打印 articles
变量,代码不会引发错误。但是,当我打印 articles.text
或 articles.get_attribute("textContent")
时,错误仍然出现。
如果有人能帮助我,那就太好了。提前致谢。
enter image description here
enter image description here
你有一个小错误。这一行,你在找到元素后点击,导致页面发生变化,找不到文章数
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()
即可