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

使用Selenium WebDriver时复制的XPath出现红色下划线是什么原因?

问题原因分析
  • 注释语法使用错误
    Python的单行注释标识符为#,你使用的//是Java、JavaScript等语言的注释语法,在Python中//代表整数除法运算符,直接放在代码行首不符合Python语法规范,因此IDE会标红提示语法错误。
  • XPath路径没有作为参数传入定位方法
    你复制的XPath路径是Selenium元素定位方法的入参,需要以字符串格式传入find_element相关方法中,不能作为独立的代码行直接存在,这也是语法报错的原因。
修正方案

如果只是暂时保留XPath备用,直接在每一行XPath前加#注释即可解决标红问题:

# //*[@id="guest_last_name"]
# //*[@id="guest_email"]
# //*[@id="btnDailyScreeningSubmit"]/button

如果需要用这些XPath完成元素定位,可参考如下代码,Selenium 4.0+版本推荐使用By.XPATH的写法:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome(executable_path='/Users/name/Desktop/Selenium/chromedriver')

url = 'https://healthscreening.schools.nyc/?type=G'
driver.get(url)

# 定位对应元素
last_name_input = driver.find_element(By.XPATH, '//*[@id="guest_last_name"]')
email_input = driver.find_element(By.XPATH, '//*[@id="guest_email"]')
submit_btn = driver.find_element(By.XPATH, '//*[@id="btnDailyScreeningSubmit"]/button')

# 后续操作示例
# last_name_input.send_keys("测试姓氏")
# email_input.send_keys("test@example.com")
# submit_btn.click()

如果使用的是Selenium 3.x旧版本,也可以沿用原有定位写法:

last_name_input = driver.find_element_by_xpath('//*[@id="guest_last_name"]')
email_input = driver.find_element_by_xpath('//*[@id="guest_email"]')
submit_btn = driver.find_element_by_xpath('//*[@id="btnDailyScreeningSubmit"]/button')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:24:01