综合使用python爬虫技术,selenium模块动态抓取“视觉中国”网站上的图片的url

一、 导入模块
import time
from selenium import webdriver
from lxml import etree
本文章纯粹用来练手,于是我使用了etree,其实光使用find_elements…的方法也可以

二、开始干活
1.首先创建driver对象

driver=webdriver.Chrome()

2.打开网站

driver.get("https://www.vcg.com/creative")

3.分析
我要抓取的是VCG的creative模块用js动态加载的图片内容
发现鼠标移过最上面一层图片导航button,下面的图片会自动切换,于是使用代码
找导航条:

jss=driver.find_elements_by_css_selector("[class='jss138 jss140']")[0]

因为我发现这个导航条的类是jss138 jss140,引用了两个类,所以使用css_selector,找到了这个导航条
接下来是
找导航条里面的button:

buttons=jss.find_elements_by_xpath("./div/button")

4.开始捕获鼠标切换到每个button下面加载的图片:
使用循环:

for button in buttons:

鼠标移至该button

webdriver.ActionChains(driver).move_to_element(button).perform()

让他停两秒,保证加载顺利

time.sleep(2)

分析图片的url所在的div
他所有图片无非是两种存储路径

1.//*[@class="jss10"]/div[2]/div/a/div/div/@style
2.//*[@class="jss10"]/div[2]/div/div/div/div/div/a/@href

于是我使用lxml模块中的etree创建一个tree获取两种图片所在的div

html=driver.page_source
    tree=etree.HTML(html.encode())
    div1=tree.xpath('//*[@class="jss10"]/div[2]/div/a/div/div/@style')
    div2=tree.xpath('//*[@class="jss10"]/div[2]/div/div/div/div/div/a/@href')

其中第一种div获取到的url可以进一步分解,我这就不再做详细分解了

完整代码如下:

import time
from selenium import webdriver
from lxml import etree

driver=webdriver.Chrome()
driver.get("https://www.vcg.com/creative")
jss=driver.find_elements_by_css_selector("[class='jss138 jss140']")[0]
buttons=jss.find_elements_by_xpath("./div/button")

for button in buttons:
    webdriver.ActionChains(driver).move_to_element(button).perform()
    time.sleep(2)
    html=driver.page_source
    tree=etree.HTML(html.encode())
    div1=tree.xpath('//*[@class="jss10"]/div[2]/div/a/div/div/@style')
    div2=tree.xpath('//*[@class="jss10"]/div[2]/div/div/div/div/div/a/@href')
    print(div1)
    print(div2)
driver.close()

这是代码显示结果:
综合使用python爬虫技术,selenium模块动态抓取“视觉中国”网站上的图片的url