|
最近学了selenium爬取淘宝商品信息的网课,于是就想着也可以依葫芦画瓢的方式来用selenium程序来爬取京东以作巩固。对代码进行了一些研究,通过不断调试,学到了很多细节上的处理。京东和淘宝一样是属于比较难采集的网站,网站的反爬机制不仅多还严。比如最常见的反爬机制封ip,一般处理就很简单,加上代理就可以,但是像京东这样的网站对ip的需求也很高,就算是使用的高匿的代理也还要做好反爬策略,不然效果也是很差的。这里分享一部分代码示例给大家参考下: from selenium import webdriver import string import zipfile # 代理服务器(产品官网 www.16yun.cn) proxyHost = "t.16yun.cn" proxyPort = "31111" # 代理验证信息 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'D:/{}_{}@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", "", "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: ["foobar.com"] } }; chrome.proxy.settings.set({value: config, scope: "regular"}, function() {}); function callbackFn(details) { return { authCredentials: { username: "${username}", password: "${password}" } }; } chrome.webRequest.onAuthRequired.addListener( callbackFn, {urls: [""]}, ['blocking'] ); """ ).substitute( host=proxy_host, port=proxy_port, username=proxy_username, password=proxy_password, scheme=scheme, ) 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) # 修改webdriver get属性 # script = ''' # Object.defineProperty(navigator, 'webdriver', { # get: () => undefined # }) # ''' # driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": script}) driver.get("http://httpbin.org/ip")代码部分主要就是代理的使用分享,在这方面有需求的小伙伴可以多了解下https://www.16yun.cn/。关于京东数据获取的更多内容今天就分享到这里,关注小编之后会分享更多的爬虫知识。
若有收获,就点个赞吧
|
|