selenium.webdriver元素定位失败

错误提示:

Traceback (most recent call last):
  File "E:/PythonData/Login/venv/logIn.py", line 18, in <module>
    driver2.switch_to.frame(driver2.find_element_by_xpath("//iframe[@id='x-URS-iframe']"))#切换到用户名和密码输入框所在的frame元素
  File "E:\PythonData\Login\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "E:\PythonData\Login\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "E:\PythonData\Login\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "E:\PythonData\Login\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//iframe[@id='x-URS-iframe']"}
  (Session info: chrome=74.0.3729.108)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17134 x86_64)
View Code

解决办法:

  可能原因:

页面元素未加载完成:可设置等待时间:

wait=WebDriverWait(driver2,10,1)#显示等待:10秒内,每1秒扫描一次

 

  可能原因:iframe id 值与实际值不一致

查看页面实际值发现:ID值为 固定字符串+ 随机数

1 id="x-URS-iframe1556246512819.8438"

 

可以使用 xpath的三种办法来解决:

driver.find_element_by_xpath
("//div[contains(@id, 'btn-attention')]")
driver.find_element_by_xpath
("//div[starts-with(@id, 'btn-attention')]")
driver.find_element_by_xpath
("//div[ends-with(@id, 'btn-attention')]"

contains(a, b) 如果a中含有字符串b,则返回true,否则返回false
starts-with(a, b) 如果a是以字符串b开头,返回true,否则返回false
ends-with(a, b) 如果a是以字符串b结尾,返回true,否则返回false

 

转载于:https://www.cnblogs.com/Yanqiqi/p/10773315.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值