首页 > 解决方案 > 使用 Selenium Python 时出现 NoSuchElementException

问题描述

我正在尝试通过单击产品并转到其详细页面来从网站上抓取每种产品的促销信息。当蜘蛛点击产品时,网页会要求它登录,我尝试了以下代码:

    def __init__(self):
        self.driver = webdriver.Chrome(executable_path = '/usr/bin/chromedriver')
...
    def start_scraping(self, response):
        self.driver.get(response.url)    
        self.driver.find_element_by_id('fm-login-id').send_keys('iamgooglepenn')
        self.driver.find_element_by_id('fm-login-password').send_keys('HelloWorld1_')
        self.driver.find_element_by_class_name('fm-button fm-submit password-login').click()
        ...

但是,当我运行它时会出现 NoSuchElementException。

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="fm-login-id"]"}
'spider_exceptions/NoSuchElementException': 14,

登录页面的HTML如下:

<div class='input-plain-wrap input-wrap-loginid'>
    <input id='fm-login-id' class='fm-text' name='fm-login-id'...>
    event
</div>

所以,我很确定 id 应该是“fm-login-id”。我能想到的可能导致这个问题的原因是这个登录页面是一个弹出窗口。 登录页面

基本上,它会在主页的中间弹出。查看站点的 HTML,可以看到登录类型似乎是一个新的 HTML 窗口

<!DOCTYPE html>
<html>event
....
<\html>

我不确定这是否是问题,如果是,如何解决?另外,是否还有其他可能导致该问题的原因?

标签: pythonseleniumselenium-webdriverscrapyselenium-chromedriver

解决方案


弹出窗口将有一个 ID。您可能必须添加f'#{popup_id}'response.url. 喜欢这个网址:https://stackoverflow.com/questions/62906380/nosuchelementexception-when-using-selenium-python/62906409#62906409。它包含#62906409因为62906409是页面中元素的 ID。


推荐阅读