代码
话不多说,直接上代码
from selenium import webdriverfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilitiesdef getSource(url): headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4882.400 QQBrowser/9.7.13059.400', 'referer':'http://www.taobao.com' } #使用copy()防止修改原代码定义dict cap = DesiredCapabilities.PHANTOMJS.copy() for key, value in headers.items(): cap['phantomjs.page.customHeaders.{}'.format(key)] = value # 不载入图片,爬页面速度会快很多 cap["phantomjs.page.settings.loadImages"] = False driver = webdriver.PhantomJS(desired_capabilities=cap) driver.get(encodeUrl(url))
部分博文提到设置User-Agent使用的是这个方法,好像也是可以的:
cap["phantomjs.page.settings.userAgent"] = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36'
检查
访问如下网址,可以回显你请求的数据,用来检查设置的header是否有效:
https://httpbin.org/get?show_env=1 例如我用如上的代码,访问这个地址,后面跟上两个实验参数: https://httpbin.org/get?show_env=1&q=nihao&bbb=c 网页返回: