使用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
相关产品推荐
相关产品推荐

