python-3.x - 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()
解决方案
我添加了无头作为争论而不是选项,它对我有用。试一下。
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
.
推荐阅读
- empirical-lang - 为什么我不能在变量上调用 load()?
- c++ - 如何改进 Lua 内部错误消息以包含行号?
- javascript - JavaScript:如何在 Chrome for iOS 上指定 blob 文件的名称?
- swift - RealityKit – arView.scene 添加 AnchorEntity
- go - gocov 不会将完整的测试覆盖结果上传到 codeclimate
- jquery - Jquery Bootstrap Accordian 常见问题解答
- algorithm - 分析确定重合虚线中的虚线是否会重叠
- android - Firebase phone auth kotlin 不会发送验证码
- javascript - Javascript禁用按钮,直到3个或更多输入字段具有值
- reactjs - 当我运行 Npm Start 时,React 页面不会在浏览器中实时更改