简体   繁体   English

为什么在 python flask 中使用 Selenium 时出现 No such element 异常?

[英]Why am I getting a No such element exception using Selenium in python flask?

I have written a program using selenium in python flask which does webscraping of a product.我在 python flask 中使用 selenium 编写了一个程序,该程序对产品进行网络抓取。 My intention is to first enter the product name(this is done programmatically)->after product is displayed-> it should display the price of product which I would be displaying in the terminal.我的意图是首先输入产品名称(这是通过编程完成的)->显示产品后->它应该显示我将在终端中显示的产品价格。 My issue however is that it doesn't scrape the website and it throws a Selenium NoSuchElementException .然而,我的问题是它不会抓取网站并且会抛出Selenium NoSuchElementException Here is my code.这是我的代码。

def scrape_johnLewis(product_name):
    website_address = 'https://www.johnlewis.com/'
    options = webdriver.ChromeOptions()
    options.add_argument('start-maximized')
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)

    browser = webdriver.Chrome(ChromeDriverManager().install(), options=options)

    browser.get(website_address)
    time.sleep(10)
    browser.implicitly_wait(20)
    browser.find_element_by_css_selector('button.c-button-yMKB7 c-button--primary-39fbj c-button--inverted-UZv88 c-button--primary-3tLoH').click()
    browser.find_element_by_id('mobileSearch').send_keys(product_name)
    browser.find_element_by_css_selector('div.input-with-submit.module-inputWrapper--63f9e > button.button.module-c-button--fe2f1').click()
    time.sleep(5)
    # browser.find_elements_by_class_name('button.module-c-button--fe2f1')[0].submit()
    product_price_raw_list = browser.find_elements_by_xpath('//div[@class="info-section_c-product-card__section__2D2D- price_c-product-card__price__3NI9k"]/span')
    product_price_list = [elem.text for elem in product_price_raw_list]
    print(product_price_list)


if __name__ == "__main__":
    scrape_johnLewis('Canon EOS 90D Digital SLR Body')

The error that I am getting is over here browser.find_element_by_css_selector('button.c-button-yMKB7 c-button--primary-39fbj c-button--inverted-UZv88 c-button--primary-3tLoH').click()我得到的错误在这里browser.find_element_by_css_selector('button.c-button-yMKB7 c-button--primary-39fbj c-button--inverted-UZv88 c-button--primary-3tLoH').click()

and here is the stacktrace:这是堆栈跟踪:

Traceback (most recent call last):
  File "scrapejohnLewis.py", line 32, in <module>
    scrape_johnLewis('Canon EOS 90D Digital SLR Body')
  File "scrapejohnLewis.py", line 20, in scrape_johnLewis
    browser.find_element_by_css_selector('button.c-button-yMKB7 c-button--primary-39fbj c-button--inverted-UZv88 c-button--primary-3tLoH').click()
  File "/home/mayureshk/.local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 598, in find_element_by_css_selector
    return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
  File "/home/mayureshk/.local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
    'value': value})['value']
  File "/home/mayureshk/.local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/home/mayureshk/.local/lib/python3.7/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":"css selector","selector":"button.c-button-yMKB7 c-button--primary-39fbj c-button--inverted-UZv88 c-button--primary-3tLoH"}
  (Session info: chrome=74.0.3729.108)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Linux 5.0.0-1034-oem-osp1 x86_64)

I have tried to replace it with find_element_by_tag_name however that didn't do the work either.我试图用 find_element_by_tag_name 替换它,但这也没有完成工作。 By inspecting the website I have come to find out the exact element but to my surprise the error says that there is no such element.通过检查网站,我找到了确切的元素,但令我惊讶的是,错误表明没有这样的元素。 What exactly could be the case?究竟可能是什么情况? Please help.请帮忙。

The cookie prompt was not managed properly, it didn't go away and hence it blocks the code beneath thus stopping Selenium in finding the element. cookie 提示没有正确管理,它没有 go 离开,因此它阻止下面的代码,从而阻止Selenium查找元素。 I've also made some tweaks to the code.我还对代码进行了一些调整。

from selenium.webdriver.common.keys import Keys

def scrape_johnLewis(product_name):
    website_address = 'https://www.johnlewis.com/'
    options = webdriver.ChromeOptions()
    options.add_argument('start-maximized')
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)

    browser = webdriver.Chrome(ChromeDriverManager(log_level='0').install(), options=options)

    browser.get(website_address)
    time.sleep(3)
    # browser.implicitly_wait(20)
    browser.find_element_by_xpath('//*[@id="pecr-cookie-banner-wrapper"]/div/div[1]/div/div[2]/button[1]').click()
    browser.find_element_by_id('desktopSearch').send_keys(product_name + Keys.ENTER)
    time.sleep(5)
    product_price_raw_list = browser.find_elements_by_xpath('//div[@class="info-section_c-product-card__section__2D2D- price_c-product-card__price__3NI9k"]/span')
    product_price_list = [elem.text for elem in product_price_raw_list]
    print(product_price_list)

# ouptut
['£1,249.00', '£1,629.99', '£1,349.99']

Also try using css_selector as the last resort if you cannot find better element locators like id , xpath , tag_name .如果找不到更好的元素定位器,例如idxpathtag_name ,也可以尝试使用css_selector作为最后的手段。

Once, I was getting the same error.有一次,我遇到了同样的错误。 You will wonder How it was fixed?你会想知道它是如何修复的?

I kept my selenium web driver by mistake, then copy the xpath from there and my code worked.我错误地保留了我的 selenium web 驱动程序,然后从那里复制 xpath 并且我的代码有效。

Then, I found that the xpath of the particular element in webdriver windows differs from the xpath of the same element in actual browser window . Then, I found that the xpath of the particular element in webdriver windows differs from the xpath of the same element in actual browser window .

There was a single extra tag being added into the path in webdriver window but not in actual browser window .webdriver window的路径中添加了一个额外的标签,但在实际浏览器 window中没有。

May be there is the same issue on your side.可能你身边也有同样的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我在 python 中没有收到 chromedriver 异常 - why i am not getting chromedriver exception in python 为什么即使元素存在于我的循环中,我也会收到 StaleElementReferenceException? (硒蟒) - Why am I getting StaleElementReferenceException even though the element is present in my loop? (Selenium Python) 即使在 selenium python 中使用 try catch 后,我也会遇到超时异常 - I am getting timeout exception even after using try catch in selenium python 我在使用 flask 的 python 中遇到语法错误,我不知道为什么 - I am getting a syntax error in python using flask and I have no idea why 为什么在尝试使用 selenium 搜索栏 select 时出现“元素不可交互”错误? - Why am I getting an "element not interactable" error when trying to select a search bar using selenium? Python Selenium:我正在获取元素未附加到页面文档错误 - Python Selenium: I am getting element is not attached to the page document error 为什么在Flask python中使用get方法时出现错误 - Why I am getting error while using get method in Flask python 为什么我无法使用 Python 和 Selenium 找到 html 元素? - Why am I unable to find html element with Python and Selenium? selenium python 为什么我没有得到图像 url? - selenium python why I am not getting image url? 为什么我收到 Python Discord 机器人异常错误 - Why am i getting a Python Discord Bot Exception Error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM