无法标记正确的元素以在 Python 中使用 Selenium 抓取网站

问题描述 投票:0回答:1

我正在尝试抓取this网站,一旦插入详细信息,该网站就会显示公用事业账单信息。该网站要求我插入一些信息并单击一些选项。

我一直在阅读有关 Selenium 以及如何实现“填写详细信息”和“单击按钮”选项的内容。然而,我发现很难理解从网站的 html 中插入什么“代码”才能使 python 代码工作。

我基本上一开始就卡住了:

url = 'https://www.facile.it/energia-dual-fuel/preventivo.html'

# Your information
name = 'Mario Rossi' # random name
email = '[email protected]' # random email
phone = '3333333333' # random number
zip_code = '20019' # some random postcode for Milan

# Initialize the Chrome WebDriver
driver = webdriver.Chrome()
# Open the website
driver.get(url)

到目前为止一切顺利,从现在开始我发现很难让它发挥作用。我尝试通过

Id
NAME
检索信息,但它并没有真正起作用。我还检查了网站的 html,但并没有真正理解从中获取什么。

name_field = driver.find_element(By.NAME, 'Nome e Cognome')
name_field.send_keys(name)


NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"[name="Nome e Cognome"]"}
  (Session info: chrome=125.0.6422.61); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception


# Also tried something like this (but it didn't work either):

name_field = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.NAME, 'Nome e Cognome')))

提供一个如何使用“单击”选项和“填写表单”选项的示例会很有帮助,以便我更好地理解如何操作。

有人可以帮我吗?

python selenium-webdriver web-scraping selenium-chromedriver
1个回答
0
投票

我假设名称字段是一个文本框。所以你需要先点击它,然后发送输入然后按回车。

  name_field = driver.find_element(By.NAME, 'Nome e Cognome')
  name_field.click()
  name_field.send_keys(name)
  name_field.send_keys(Keys.RETURN)

如果仍然不行,那么尝试使用一些睡眠或等待函数来等待写入完全加载然后再尝试。

© www.soinside.com 2019 - 2024. All rights reserved.