没有这样的元素:无法在生产环境中使用chromedriver和Selenium定位元素

Mel*_*hoa 9 python selenium selenium-chromedriver selenium-webdriver webdriverwait

我有硒chromedriver的问题,我无法弄清楚是什么导致它.几周前一切正常,但突然出现这个错误.问题来自以下功能.

 def login_(browser):
    try:
        browser.get("some_url")
        # user credentials
        user = browser.find_element_by_xpath('//*[@id="username"]')
        user.send_keys(config('user'))
        password = browser.find_element_by_xpath('//*[@id="password"]')
        password.send_keys(config('pass'))
        login = browser.find_element_by_xpath('/html/body/div[1]/div/button')
        login.send_keys("\n")
        time.sleep(1)
        sidebar = browser.find_element_by_xpath('//*[@id="sidebar"]/ul/li[1]/a')
        sidebar.send_keys("\n")
        app_submit = browser.find_element_by_xpath('//*[@id="sidebar"]/ul/li[1]/ul/li[1]/a')
        app_submit.send_keys("\n")
    except TimeoutException or NoSuchElementException:
        raise LoginException
Run Code Online (Sandbox Code Playgroud)

此功能在开发环境(macOS 10.11)中没有问题,但在生产环境中引发以下错误:

Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="sidebar"]/ul/li[1]/a"}
(Session info: headless chrome=67.0.3396.79)
(Driver info: chromedriver=2.40.565383 (76257d1ab79276b2d53ee97XXX),platform=Linux 4.4.0-116-generic x86_64)
Run Code Online (Sandbox Code Playgroud)

我已经在每个环境中更新了Chrome和chromedriver(分别为v67和2.40).我也给了它更多time.sleep(15).但问题仍然存在.我最新的猜测是,webdriver的初始化可能无法正常工作:

def initiate_webdriver():
   option = webdriver.ChromeOptions()
   option.binary_location = config('GOOGLE_CHROME_BIN')
   option.add_argument('--disable-gpu')
   option.add_argument('window-size=1600,900')
   option.add_argument('--no-sandbox')
   if not config('DEBUG', cast=bool):
       display = Display(visible=0, size=(1600, 900))
       display.start()
       option.add_argument("--headless")
   else:
       option.add_argument("--incognito")
   return webdriver.Chrome(executable_path=config('CHROMEDRIVER_PATH'), chrome_options=option)
Run Code Online (Sandbox Code Playgroud)

因为,如果Display不工作,那么可能没有提到sidebar但是其他一些按钮.

所以我的问题是:有没有人有类似的问题?有没有办法知道驱动程序在寻找这样一个元素时显示的页面是什么?

小智 4

据报告,在您提供登录信息后,未找到元素错误,因此我认为登录失败并且页面重定向到某个地方。您可以使用屏幕截图选项对页面进行屏幕截图,然后查看驱动程序加载了哪个页面。

driver.save_screenshot("path to save screen.jpeg")
Run Code Online (Sandbox Code Playgroud)

您还可以保存原始 html 代码并检查同一页面。

网络驱动程序截图

在 Python 中使用 Selenium 在 Firefox 上保存网页


归档时间:

查看次数:

3017 次

最近记录:

7 年,6 月 前