【问题标题】:previous web crawler doesn't recognize element id以前的网络爬虫无法识别元素 ID
【发布时间】:2023-03-23 18:42:02
【问题描述】:

我是网络爬虫任务的新手。之前我试过下面这个简单的爬虫,效果很好。 最近我回到代码并尝试在爬虫上做更多事情,但是 browser.find_element_by_id("lst-ib") 不起作用,我收到错误提示

' 没有这样的元素:无法找到元素:{"method":"css selector","selector":"[id="lst-ib"]"} (会话信息:chrome=84.0.4147.89)'

为了解决我的问题,我尝试从检查中找到谷歌页面的输入文本框的 xpath。总是这样吗?我们为爬虫定义的 id 或 css 选择器是否会定期更改,我们应该更新代码吗?

  from selenium import webdriver

  url = "https://www.google.com"

  browser = webdriver.Chrome(executable_path = "chromedriver")
  browser.get(url)
  

  #inputElement = browser.find_element_by_id("lst-ib")

  # I replace the xpath with previous id
  inputElement = 
  browser.find_element_by_xpath("/html/body/div/div[2]/form/div[2]/div[1]/div[1]/div/div[2]/input")

  inputElement.send_keys("my input search text")
  inputElement.submit()

  browser.quit()

【问题讨论】:

  • 试试inputElement = browser.find_element_by_xpath('//input[@title="Search"]')
  • @JaSON 我仍然收到此错误:无法找到元素:{"method":"xpath","selector":"//input[@title="Search"]"} (Session信息:铬=84.0.4147.89)。我做错了什么吗?
  • this discussion 对您有帮助吗?
  • @Mahsa ,然后尝试申请ExplicitWait

标签: css selenium selenium-webdriver web-crawler


【解决方案1】:

在 xpath 下面试试:

inputElement = 
  browser.find_element_by_xpath("//body[@id='gsr']/div[@id='viewport']/div[@id='searchform']/form[@id='tsf']/div/div/div/div/div/input[1]")

inputElement.send_keys("my input search text") 

您的解决方案:

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
import time
driver = webdriver.Chrome(executable_path=r"path of chrome driver")

wait = WebDriverWait(driver, 10)
driver.get("https://www.google.com")

inputElement = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "/html/body/div/div[2]/form/div[2]/div[1]/div[1]/div/div[2]/input")))
inputElement.send_keys("my input search text")

输出:

【讨论】:

  • 它确实有效,你知道为什么之前的 inputElement = browser.find_element_by_id("lst-ib") 不再有效了吗?你如何生成这个xpath?我使用了检查中的复制 xpath,我得到了: /html/body/div/div[2]/form/div[2]/div[1]/div[1]/div/div[2]/input 这是不同的你的
  • 我也添加了你的例子,所以你需要使用 WebDriverWait 来避免同步问题。在您的解决方案中,您在运行时 Web 驱动程序通过 DOM 搜索您的元素期间使用绝对路径,并且因为您使用的是绝对 xpath,它需要时间来定位您的元素。尽量避免使用 aabsolute xpath 。此外,使用 WebDriverWait 来避免同步问题总是好的
  • @Mahsa :如果您的问题得到解决,您是否愿意接受回答并点击投票按钮。
猜你喜欢
  • 2012-08-01
  • 2012-01-14
  • 1970-01-01
  • 2014-10-04
  • 1970-01-01
  • 2011-12-11
  • 1970-01-01
相关资源
最近更新 更多