爬取虎牙直播图片的分析
一、直接放源码
import requests
from lxml import etree
url='https://www.huya.com/g/4079'
r=requests.get(url)
data=etree.HTML(r.text)
girls=data.xpath('//img[@class="pic"]') #匹配
for girl in girls:
img_url=girl.xpath('./@data-original')[0]
name=girl.xpath('./@alt')
img=requests.get(img_url)
with open('./image/%s.jpg' %name,'wb') as jpg:
jpg.write(img.content)
print("<%s> 下载成功" %name)
注:image是在该py文件外部创建的文件夹,可以从这段代码看出来:
with open('./image/%s.jpg' %name,'wb') as jpg:
二、代码分析
首先在虎牙官网找到需要爬取的主播图片的具体网址,即:
<img class="pic" data-original="https://anchorpost.msstatic.com/cdnimage/anchorpost/1029/e0/bba5da111110676c3a1e05b2795558_4079_1631157512.jpg?imageview/4/0/w/338/h/190/blur/1" src="https://anchorpost.msstatic.com/cdnimage/anchorpost/1029/e0/bba5da111110676c3a1e05b2795558_4079_1631157512.jpg?imageview/4/0/w/338/h/190/blur/1/format/webp" data-default-img="338x190" alt="千凰-星瑶仙境的直播" title="千凰-星瑶仙境的直播">
由于代码中使用了xpath,我们先分析一下xpath的语法:
代码中使用了“//”即可以在子孙节点中查找,那么“girls=data.xpath(’//img[@class=“pic”]’) #匹配”
就可以直接定位到上文红框的代码处。
需要注意的是,每个图片都是套在li标签中的,所以生成的girls是一个存放了很多组数据的数组.
接下来对每一组数据,获取图片地址和图片名:
for girl in girls:
img_url=girl.xpath('./@data-original')[0]
name=girl.xpath('./@alt')
因为是同级的标签,所以用的是 ./
最后是对图片的处理:
with open('./image/%s.jpg' %name,'wb') as jpg:
jpg.write(img.content)
print("<%s> 下载成功" %name)
在同级文件夹的image中写入图片,wb表示二进制形式,然后用%s占位来显示每一个图片名称。
总结
主要就是用到etree和lxml两个库,在安装的时候笔者花了不少功夫,如果有问题可以询问我,尽量及时回复。