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

 

posted @ 2019-04-26 11:28  烟七七  阅读(648)  评论(0编辑  收藏  举报