【问题标题】:How to get first Element of Chrome using Selenium with Python?如何使用 Selenium 和 Python 获得第一个 Chrome 元素?
【发布时间】:2020-08-11 16:54:40
【问题描述】:

这是我目前获取页面第一个元素(或父元素)的方法:

first_element = page_or_parent.find_element_by_xpath('//*')

我最近才遇到的问题(Chrome 和chromedriver 84 版)是有时这会引发异常:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*"}

再次调用相同的方法通常会检索元素,因此我认为文档树暂时不可用。但是,网络驱动程序日志并没有显示任何异常:

[1597164661.317][INFO]: [d88526be26bd6364d1b0ed2dab9d5733] COMMAND FindElement {
"using": "xpath",
"value": "//*"
}
[1597164661.317][INFO]: Waiting for pending navigations...
[1597164661.317][INFO]: Done waiting for pending navigations. Status: ok
[1597164661.418][INFO]: Waiting for pending navigations...
[1597164661.418][INFO]: Done waiting for pending navigations. Status: ok
[1597164661.418][INFO]: [d88526be26bd6364d1b0ed2dab9d5733] RESPONSE FindElement ERROR no such element: Unable to locate element: {"method":"xpath","selector":"//*"}
(Session info: chrome=84.0.4147.89)

然后我的主要问题是如何可靠地获取第一个元素

有没有比我现在使用 XPath 更好的方法?我考虑过find_elements_by_xpath()(复数),但如果有很多元素,那么可能会生成大量数据并且运行速度会慢得多。目前我能想到的唯一解决方案是在异常发生时捕获异常,等待/睡眠,然后重试,但感觉很脏。

【问题讨论】:

    标签: python selenium xpath selenium-chromedriver


    【解决方案1】:

    您必须等待一段时间才能完全加载页面,然后您才能恢复脚本。否则你也可以使用wait,如下图-

    # Import 
    from selenium.webdriver.support import expected_conditions
    
    wait = WebDriverWait(driver, 5)
    
    wait.until(expected_conditions.presence_of_element_located((By.XPATH, "Your XPATH")))
    

    【讨论】:

    • 遇到问题时页面已完全加载;我确认文档就绪状态为"complete"
    • 您是否尝试过使用上述解决方案中提到的expected_condition?如果是,那么您遇到了什么错误?相同的“NoSuchElementException”?
    • 它会起作用——它和我已经验证过的睡眠一样。我认为这是 Linux 上的 Chrome 问题,因为它是最近才出现的,否则代码会不停地运行 2 年。我不会将 sleeps 添加到获取第一个元素的辅助函数中;所以现在我只处理异常
    猜你喜欢
    • 2020-01-29
    • 2022-01-02
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多