You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Selenium无法定位网页元素进行爬取求助

解决方案

你遇到的问题核心是元素定位器错误(误用了输入框的显示文本而非实际HTML属性),再加上网站的Cookie弹窗会干扰后续交互。以下是完整的可运行代码示例,附带关键步骤说明:


1. 前置依赖

确保导入Selenium核心模块:

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

2. 完整代码实现

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

# 测试数据
name = 'Mario Rossi'
email = 'test@live.it'
phone = '3333333333'
zip_code = '20019'

# 初始化浏览器
driver = webdriver.Chrome()
driver.maximize_window()
driver.get(url)

try:
    # 步骤1:处理Cookie同意弹窗(必须先关闭,否则会遮挡元素)
    cookie_accept_btn = WebDriverWait(driver, 15).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[data-testid="cookie-accept-all"]'))
    )
    cookie_accept_btn.click()

    # 步骤2:填写姓名(实际HTML中name属性为'name',不是显示的"Nome e Cognome")
    name_field = WebDriverWait(driver, 15).until(
        EC.visibility_of_element_located((By.NAME, 'name'))
    )
    name_field.send_keys(name)

    # 步骤3:填写邮箱
    email_field = WebDriverWait(driver, 15).until(
        EC.visibility_of_element_located((By.NAME, 'email'))
    )
    email_field.send_keys(email)

    # 步骤4:填写手机号
    phone_field = WebDriverWait(driver, 15).until(
        EC.visibility_of_element_located((By.NAME, 'phone'))
    )
    phone_field.send_keys(phone)

    # 步骤5:填写邮编
    zip_field = WebDriverWait(driver, 15).until(
        EC.visibility_of_element_located((By.NAME, 'zipCode'))
    )
    zip_field.send_keys(zip_code)

    # 步骤6:点击继续按钮(可根据后续流程调整定位器)
    next_btn = WebDriverWait(driver, 15).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[data-testid="submit-button"]'))
    )
    next_btn.click()

except TimeoutException as e:
    print(f"元素加载超时: {e}")
finally:
    # 可选:操作完成后关闭浏览器,或注释该行保持窗口打开
    # driver.quit()
    pass

关键注意事项

  • Cookie弹窗优先级:欧洲网站普遍强制显示Cookie授权弹窗,不关闭会阻止后续元素交互,必须优先处理。
  • 正确定位元素:不要用输入框的显示文本当定位器,要通过浏览器开发者工具(F12)查看元素的实际HTML属性(比如name/id)。
  • 显式等待:用WebDriverWait替代直接查找元素,避免页面动态加载导致的NoSuchElementException。
  • 定位器选择:优先用name/id,其次用CSS选择器(比XPath稳定性更高)。

内容的提问来源于stack exchange,提问作者Rollo99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 18:02:41