Python使用selenium+chrome进行抓包
Python3 + selenium + Chrome浏览器
本机需要安装 chrome浏览器
下载 chromedriver.exe
谷歌浏览器中输入:chrome://version/ 就能查看当前浏览器版本
如图所示,浏览器版本为:94.0.4606.81
下载 chromedriver.exe ,版本需要和浏览器版本保持一致,如果找不到相同的版本号,则选择一个最接近的,可兼容
chromedriver下载地址
下载地址:http://chromedriver.storage.googleapis.com/index.html
这里 chromedriver.exe 没有版本号:94.0.4606.81,我就下载了:94.0.4606.61
安装 selenium
Python 全选
pip install selenium
python代码
Python 全选
# coding=utf-8
import requests
import re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# 提取ip
resp = requests.get(
"http://tiqu.pyhttp.taolop.com/getflowip?******"
)
ip = resp.text
if re.match(
r'(?:(?:25[0-5]|2[0-4]\d|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)',
ip) is None:
exit("IP 不正确")
ip_arr = ip.split(":")
print(ip_arr)
# 请求地址
targetUrl = "http://tools.jocsoft.cn/ip"
# targetUrl = "http://www.yesdotnet.com?q=test"
# 代理服务器
proxyHost = ip_arr[0]
proxyPort = ip_arr[1]
proxyType = 'http'
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
# 设置代理
chrome_options.add_argument("--proxy-server=http://%(host)s:%(port)s" % {
"host": proxyHost,
"port": proxyPort,
})
# 一定要注意,=两边不能有空格,不能是这样--proxy-server = http://202.20.16.82:10152
# executable_path 要设置绝对路径,相对路径用不了,不知道为什么,这里就方便放在了D盘中
driver = webdriver.Chrome(executable_path='D:/chromedriver/chromedriver.exe',
chrome_options=chrome_options)
driver.get(targetUrl)
print(driver.title)
print(driver.page_source.encode("utf-8"))
driver.quit()
注意
webdriver.Chrome excutable_path
参数要设置 绝对路径
,网上有说设置相对路径的,还有path设置的,但是我这里都会报错,只有 绝对路径
才能够正常使用
参数设置错误报错信息如下:
excutable_path报错信息
发生异常: WebDriverException
Message: 'chromedriver.exe' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
During handling of the above exception, another exception occurred: File "C:\Users\XQ-Garson\Desktop\Python\gz\test3.py", line 41, in <module> chrome_options=chrome_options)
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 管理员