在Python中将Headless Chrome与Selenium结合使用

郎言
2023-12-01


Headless Chrome and regular Chrome have the same capabilities, and running them with Selenium is a very similar process. The difference is that Headless Chrome does not generate any sort of user interface. In other words, no browser is visibly launched.

无头Chrome和普通Chrome具有相同的功能,并且使用Selenium运行它们的过程非常相似。 区别在于Headless Chrome不会生成任何类型的用户界面。 换句话说,没有浏览器被启动。

If you happen to be web scraping with Selenium, it’s often helpful to see what exactly the browser is doing in real time for development and debugging purposes. However, using headless mode can be great if your script is working and you don’t want to be bothered with an open browser. And even better, a headless browser should generally run faster than its headed counterpart, given that it doesn’t require the extra resources normally needed to visually render everything happening in the browser.

如果您碰巧是使用Selenium进行Web抓取,通常对于实时查看浏览器在进行开发和调试时所做的工作通常很有帮助。 但是,如果您的脚本正在运行并且不想被打开的浏览器所困扰,那么使用无头模式可能会很棒。 甚至更好的是,无头浏览器通常应比同类浏览器运行得更快,因为它不需要通常所需的额外资源来可视化呈现浏览器中发生的所有事情。

To run Headless Chrome, you’ll first need to set up Selenium.

要运行Headless Chrome,您首先需要设置Selenium

Once you’ve got Selenium working, using Headless Chrome is a breeze. For example, let’s see if we can get to DuckDuckGo‘s home page.

一旦Selenium正常运行,使用Headless Chrome变得轻而易举。 例如,让我们看看是否可以访问DuckDuckGo的主页。

Since Headless Chrome has no visual browser, we’ll take a screenshot to confirm what the browser is doing.

由于无头Chrome没有视觉浏览器,因此我们将截屏以确认浏览器正在做什么。

from selenium import webdriver

chromedriver = "C:UsersgraysonDownloadschromedriver.exe"

options = webdriver.ChromeOptions()
options.add_argument('headless') # engage headless mode
options.add_argument('window-size=1200x600') # setting window size is optional

browser = webdriver.Chrome(executable_path=chromedriver, chrome_options=options)

browser.get("https://www.duckduckgo.com")

browser.save_screenshot('C:UsersgraysonDownloadsheadless_chrome_test.png')

browser.quit()

翻译自: https://www.pybloggers.com/2018/03/using-headless-chrome-with-selenium-in-python/

 类似资料: