【问题标题】:Error when using headless Chrome in Selenium在 Selenium 中使用无头 Chrome 时出错
【发布时间】:2021-10-02 08:18:43
【问题描述】:

我正在尝试在网站上抓取一些内容。为了获得网站上的动态内容,我求助于 selenium。但是当我尝试使用 headless Chrome 时,每次打开页面时终端都会输出以下警告/错误消息。

DevTools listening on ws://127.0.0.1:9234/devtools/browser/3b04bcfa-0f81-4131-813f-9db6f63711fa
[1002/145548.271:ERROR:gpu_init.cc(453)] Passthrough is not supported, GL is swiftshader, ANGLE is
[1002/145548.391:ERROR:command_buffer_proxy_impl.cc(125)] ContextResult::kTransientFailure: Failed to send GpuControl.Cr
eateCommandBuffer.
[1002/145549.272:INFO:CONSOLE(0)] "Error with Permissions-Policy header: Unrecognized feature: 'interest-cohort'.", sour
ce:  (0)

此外,当我尝试在 Google Colab 中进行抓取时,结果似乎并不好,甚至不稳定。那就是我连续尝试了,抓取内容的长度也不一样。当我使用 non-headless 将相同的代码在本地运行时,Chrome 似乎更好。设置如下。

from selenium import webdriver
from bs4 import BeautifulSoup

options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Chrome(options=options)

在我在 Google Colab 中跑步之前。我运行社区中提到的以下命令。

!apt update
!apt install chromium-chromedriver
!pip install selenium

系统

OS: windows 10 + python 3.7 + Chrome 93.0.x + selenium 1.26.6

【问题讨论】:

  • 指定无头时为什么要调用 maximise_window?
  • @BrutusForcus 感谢您的回复。当我尝试 non-headless Chrome 时,我首先设置它以最大化我页面的加载内容。抱歉,当我转向 headless 时忘记删除它。我删除了它,但问题仍然存在。

标签: python selenium google-chrome selenium-webdriver


【解决方案1】:

这是一个从link 抓取数据并浏览网页左侧显示“摘要”的部分内容的示例:

import time as time
!apt-get update
!apt install chromium-chromedriver
!which chromedriver
!pip install selenium
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.expected_conditions import presence_of_element_located
!pip install page_objects
import page_objects
from page_objects import PageObject, PageElement
time.sleep(1)
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('chromedriver',options = options)
driver.implicitly_wait(3)
driver.get('https://finance.yahoo.com/quote/AAPL?.tsrc=applewf')
open('source.html', 'w').write(driver.page_source)
parent_tab = driver.current_window_handle
links = driver.find_elements_by_tag_name('a')
for i in links:
  if 'Summary' in i.get_attribute('text'):
    if 'Bid' in driver.find_element_by_tag_name('body').text:
      print(driver.find_element_by_tag_name('body').text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 1970-01-01
    • 2021-08-09
    • 2017-07-07
    相关资源
    最近更新 更多