【问题标题】:How to get data using Selenium wihout opening Chrome browser?如何在不打开 Chrome 浏览器的情况下使用 Selenium 获取数据?
【发布时间】:2021-06-29 17:25:26
【问题描述】:

我正在尝试抓取 Amazon product prices。我想在不打开 Chrome 浏览器的情况下抓取价格文本。我在互联网上搜索了这个,但它没有帮助我。

这是我的代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# Driver and link
driver = webdriver.Chrome('C:/Users/musta/Desktop/chromedriver.exe')
driver.get("https://www.amazon.com/dp/b07h9fldcd")

getText = driver.find_element_by_class_name("a-section a-spacing-micro").get_attribute("textContent")
print(getText)

driver.close()

但这没有用。它一直给我这个错误信息:

Traceback (most recent call last):
  File "C:\Users\musta\Desktop\asd.py", line 8, in <module>
    getText = driver.find_element_by_class_name("a-section a-spacing-micro").get_attribute("textContent")
  File "C:\Users\musta\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name
    return self.find_element(by=By.CLASS_NAME, value=name)
  File "C:\Users\musta\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\musta\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\musta\AppData\Local\Programs\Python\Python37\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":"css selector","selector":".a-section a-spacing-micro"}
  (Session info: chrome=91.0.4472.114)

我该怎么办?我被困在这里。我想在不打开 Chrome 浏览器的情况下从给定的div 中获取价格。希望你明白我的意思。

【问题讨论】:

  • 您的意思是在无头模式下运行脚本吗?还有你想得到什么价格?

标签: python arrays string selenium web-scraping


【解决方案1】:

我认为你需要无头浏览器:

options = webdriver.ChromeOptions()
options.add_argument("--headless")
options.add_argument("start-maximized")
driver = webdriver.Chrome(r'C:/Users/musta/Desktop/chromedriver.exe', options = options)
driver.get("https://www.amazon.com/dp/b07h9fldcd")

关于您的错误,Selenium 类名中的空格不能使用:

所以不是这个,

.a-section a-spacing-micro

使用 css 执行此操作:

.a-section.a-spacing-micro

所以代码应该是这样的:

getText = driver.find_element_by_css_selector(".a-section.a-spacing-micro").get_attribute("innerHTML")
print(getText.strip())

如果它只是你想要的价格,试试这个 css:

span#price_inside_buybox

在代码中它看起来像这样:

getText = driver.find_element_by_css_selector("span#price_inside_buybox
").text
print(getText.strip())

【讨论】:

    【解决方案2】:

    您的查询中有两个问题:

    1. 您可以在无头模式下打开 chrome 浏览器,使其不会在前端呈现
    2. 尝试检查元素并确认您用于获取属性的 id/类名称

    【讨论】:

      猜你喜欢
      • 2016-05-10
      • 2018-08-04
      • 2015-03-21
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 2012-01-26
      • 2020-10-08
      相关资源
      最近更新 更多