python爬虫高级案例-动态加载页面和代理
前言:本篇文章提供了动态加载网页的解决方案,主要是针对一些懒加载和动态js加载,导致我们用requests库 ,一次爬取不到的时候,所产生的技术方案。
上干货
方案就是:Selenium+PhantomJS
这里的 **PhantomJS** 就是一个没有图形界面的浏览器,selenium+PhantomJS 的方案就是从直接HTML解析->分析JS->webkit->headless浏览器来操作web页面的selenium
下载与安装:
首先我们需要下载PhantomJS:(https://phantomjs.org/download.html)。
再安装 selenium:
pip install selenium
操作:
我们需要把PhantomJS和python脚本放在同一个文件夹下,生成 selenium_test.py 脚本
代码:
#引入selenium中的webdriver
from selenium import webdriver
import time
driver =webdriver.PhantomJS(executable_path="phantomjs.exe")
driver.get("https://item.jd.com/100037768718.html")
time.sleep(5)
print(driver.find_element_by_xpath('//*[@id="ssd-vc-shopActivity"]/ul/li/a/div/img/@src').text)
如上代码所示,可以获得动态加载数据
代理
:
#引入selenium中的webdriver
from selenium import webdriver
import time
ip = "xxx"
port = "xxx"
proxy_ip = proxy_ip = 'socks5://{}:{}'.format(ip, port)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % proxy_ip)
driver =webdriver.PhantomJS(executable_path="phantomjs.exe", options=chrome_options)
driver.get("https://item.jd.com/100037768718.html")
time.sleep(3)
print(driver.find_element_by_xpath('//*[@id="ssd-vc-shopActivity"]/ul/li/a/div/img/@src'))