对于python爬虫的相关知识之前分享了很多,这回来说说如何利用selenium自动化获取网页信息。通常对于异步加载的网页,我们需要查找网页的真正请求,并且去构造请求参数,最后才能得到真正的请求网址。而利用selenium通过模拟浏览器操作,则无需去考虑那么多,做到可见即可爬。当然带来便捷的同时,也有着不利,比如说时间上会有所增加,效率降低。可是对于业余爬虫而言,更快的爬取,并不是那么的重要。
首先在电脑的PyCharm上安装selenium,然后下载与电脑上谷歌浏览器相对应版本的ChromeDriver。项目目标以针对京东商城笔记本的网页进行分析,这回只要在网页源码上分析,就可以获取笔记本价格、标题、评论数、商家名称、商家性质。
像京东这样的电商网站,反爬技术会更严,我们在访问的过程不能直接爬取,特别是在针对限制IP访问这方面做的更严,所以这里我们在做了反爬措施的基础上要加上优质代理去访问,优质代理并不多,经过网上多次测试对比评估,发现亿牛云效果还可以,长期使用是比较好的选择。这里我们通过添加他们提供的爬虫隧道加强版去爬取,代码实现过程如下所示,
代码语言:javascript复制 from selenium import webdriver
import string
import zipfile
# 代理服务器(产品官网 www.16yun.cn)
proxyHost = "t.16yun.cn"
proxyPort = "3111"
# 代理验证信息
proxyUser = "username"
proxyPass = "password"
def create_proxy_auth_extension(proxy_host, proxy_port,
proxy_username, proxy_password,
scheme='http', plugin_path=None):
if plugin_path is None:
plugin_path = r'/tmp/{}_{}@t.16yun.zip'.format(proxy_username, proxy_password)
manifest_json = """
{
"version": "1.0.0",
"manifest_version": 2,
"name": "16YUN Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
"""
background_js = string.Template(
"""
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "${scheme}",
host: "${host}",
port: parseInt(${port})
},
bypassList: ["localhost"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "${username}",
password: "${password}"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
"""
).substitute(
host=proxy_host,
port=proxy_port,
username=proxy_username,
password=proxy_password,
scheme=scheme,
)
print(background_js)
with zipfile.ZipFile(plugin_path, 'w') as zp:
zp.writestr("manifest.json", manifest_json)
zp.writestr("background.js", background_js)
return plugin_path
proxy_auth_plugin_path = create_proxy_auth_extension(
proxy_host=proxyHost,
proxy_port=proxyPort,
proxy_username=proxyUser,
proxy_password=proxyPass)
option = webdriver.ChromeOptions()
option.add_argument("--start-maximized")
# 如报错 chrome-extensions
# option.add_argument("--disable-extensions")
option.add_extension(proxy_auth_plugin_path)
# 关闭webdriver的一些标志
# option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(
chrome_options=option,
executable_path="./chromdriver"
)
# 修改webdriver get属性
# script = '''
# Object.defineProperty(navigator, 'webdriver', {
# get: () => undefined
# })
# '''
# driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": script})
driver.get("https://httpbin.org/ip")