首页 > 解决方案 > Chrome 驱动程序不能与 Python 和 Selenium 一起工作?

问题描述

我是使用 Python 进行 Selenium 编程的新手。该代码在没有 --headless 参数的情况下可以正常工作,但是当我尝试无头运行它时根本不会执行。有人可以帮我解决吗?

下面是我的示例代码,我使用的是 Python 3。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import time
import requests
from selenium.webdriver.chrome.options import Options

options = Options()
options.set_headless(headless=True)
driver = webdriver.Chrome(chrome_options=options, executable_path=r'E:/Python/[FreeTutorials.Us] Udemy - python-master-web-scraping-course-doing-20-real-projects/03 Step  _ Download HTML Content/chromedriver.exe')
driver.get("https://www.tirerack.com/survey/ValidationServlet?autoYear=2006&autoMake=Porsche&autoModel=911%20Carrera%20S%20Cabriolet&newDesktop=true")
print ("Headless Chrome Initialized")

html_doc=driver.page_source
soup= BeautifulSoup(html_doc,'lxml')

print(soup)
driver.quit()

标签: python-3.xwebweb-scraping

解决方案


我添加了无头作为争论而不是选项,它对我有用。试一下。

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

chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='path to your chromedriver')
driver.get('https://stackoverflow.com/')

注意:始终将您的 chromedriver 保存在 python 的主路径中,即C:\Python34.


推荐阅读