使用无头铬Webdri运行Selenium

2024-04-24 23:14:01 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着用硒来做一些东西,我真的很想快点。

所以我的想法是用无头的chrome运行它会让我的脚本更快。

首先,这个假设是正确的,还是我用一个无头驱动程序运行我的脚本无关紧要?

不管怎样,我还是想让它无头运行,但我不知何故做不到,我尝试了不同的事情,大多数人建议它将工作在这里说,在十月更新

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

但当我尝试的时候,我得到了奇怪的控制台输出,但它似乎仍然不起作用。

任何提普感谢。


Tags: toinbrowser脚本modeconfigure驱动程序chrome
3条回答
from time import sleep

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--headless")

driver = webdriver.Chrome(executable_path="./chromedriver", options=chrome_options)
url = "https://stackoverflow.com/questions/53657215/running-selenium-with-headless-chrome-webdriver"
driver.get(url)

sleep(5)

h1 = driver.find_element_by_xpath("//h1[@itemprop='name']").text
print(h1)

然后我在本地机器上运行脚本

➜ python script.py
Running Selenium with Headless Chrome Webdriver

它是工作的,它是无头铬。

如果您使用的是Linux环境,可能还需要添加--no-sandbox以及特定的窗口大小设置。如果正确设置用户容器,则在Windows上不需要--no-sandbox标志。

仅在Windows上使用--disable-gpu。其他平台不再需要它。--disable-gpu标志是一些bug的临时解决方案。

//Headless chrome browser and configure
            WebDriverManager.chromedriver().setup();
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.addArguments("--no-sandbox");
            chromeOptions.addArguments("--headless");
            chromeOptions.addArguments("disable-gpu");
//          chromeOptions.addArguments("window-size=1400,2100"); // Linux should be activate
            driver = new ChromeDriver(chromeOptions);

要运行chrome headless,只需通过chrome_options.add_argument添加--headless,即:

from selenium import webdriver from selenium.webdriver.chrome.options import Options
chrome_options = Options()
#chrome_options.add_argument("--disable-extensions")
#chrome_options.add_argument("--disable-gpu")
#chrome_options.add_argument("--no-sandbox) # linux only
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
start_url = "https://duckgo.com"
driver.get(start_url)
print(driver.page_source.encode("utf-8"))
driver.quit()
# b'<!DOCTYPE html><html xmlns="http://www....

So my thought is that running it with headless chrome would make my script faster.

尝试使用chrome选项,比如--disable-extensions--disable-gpu,并对其进行基准测试,但我认为没有太大的改进。


引用:headless-chrome

Note: As of today, when running chrome headless, you should include the  --disable-gpu flag if you're running on Windows. See crbug.com/737678.

相关问题 更多 >