需求:urlopen得到的数据不正确,发现是因为界面经过js渲染
,故使用selenium
尝试一下。
1. 安装
brew install selenium
brew install phantoms
配合Chrome
使用需要安装chromedriver
:
- 下载地址 注意驱动版本与浏览器版本要对应
- 将下载的可执行文件(chromedriver) 移动到/usr/bin下
最后,把 phantoms 路径添加到 bash 中,source一下生效。
export PHANTOMJS_HOME=/usr/local/Cellar/phantomjs/phantomjs-2.1.1-macosx
export PATH=$PATH:$PHANTOMJS_HOME/bin
2. 使用selenium
简单测试一下:
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
获取网页内容: driver.page_source
3. selenium+PhantomJs
browser = webdriver.PhantomJS(executable_path="/usr/local/Cellar/phantomjs/phantomjs-2.1.1-macosx/bin/phantomjs")
browser.start_session(webdriver.DesiredCapabilities.PHANTOMJS)
# 设置超时时间
browser.set_page_load_timeout(50)
browser.set_script_timeout(50)
browser.get("http://www.baidu.com")
可以通过 browser.find_element_by_class_name
等接口拿到想要的数据。
保存截图
browser.save_screenshot("baidu.png")
4. 设置代理
# 利用DesiredCapabilities(代理设置)参数值
proxy = webdriver.Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = ip //ip地址
# 将代理设置添加到 webdriver.DesiredCapabilities.PHANTOMJS 中 proxy.add_to_capabilities(webdriver.DesiredCapabilities.PHANTOMJS)
5. 设置header
desired_capabilities = webdriver.DesiredCapabilities.PHANTOMJS.copy()
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'User-Agent': ' '
}
for key, value in headers.items():
desired_capabilities['phantomjs.page.customHeaders.{}'.format(key)] = value
browser = webdriver.PhantomJS(desired_capabilities=desired_capabilities,executable_path="/usr/local/Cellar/phantomjs/phantomjs-2.1.1-macosx/bin/phantomjs")