在上一篇文章的基础上增加获取百度贴吧的头像图片的功能,使用到的技术为XPath,Requests,具体实现如下:
1. 查看网页源代码
测试网页链接:http://tieba.baidu.com/p/3522395718?pn=1 通过Chrome定位头像的HTML的代码
每一楼层的标签是:
class=\"l_post j_l_post l_post_bright \"
从楼层开始,直到定位到照片顺序应该是
2. 提取XPath信息
通过XPath一步步获取到这一层,提取到这个标签中的src就可以获取到图片的url
ImgLink = ImgFilter.xpath(\'//div[@class=\"l_post j_l_post l_post_bright \"]\')[0]
links = ImgLink.xpath(\'//div[@class=\"d_author\"]/ul/li/div[@class=\"icon_relative j_user_card\"]/a/img/@data-tb-lazyload\')
这里会遇到一个问题,如果第二个XPath的条件是/img/@src则会遇到一个问题:
使用requests获取到的html会有很多空白的头像
\'http://tb2.bdstatic.com/tb/static-pb/img/head_80.jpg\'
这是因为网页是分步加载的,首先使用默认的头像展示,再逐步下载自定义头像替换,因此还要得到自定义头像的地址,通过分析网页代码,可以发现:
“data-tb-lazyload”这个才是真正的自定义头像的链接地址
3. 去掉获取到的链接中的重复值
由于贴吧的不同的楼层是有可能是同一个人,即同一个头像的;为了节省空间,我们要去除掉重复的图像,在Python中可以通过函数set()去除列表重复值
links = list(set(links))
测试一下:
print(\"before set list:{0}\".format(len(links)))
links = list(set(links))
print(\"after set list:{0}\".format(len(links)))
测试结果:
before set list:27
after set list:21
成功消除掉了重复的链接
4.将链接存储到jpeg文件
Requests库中包含了获取数据的方法get(),可以使用该方法将链接存储到文件中
with open(\"img{0}.jpeg\".format(i),\"wb\") as code:
code.write(graphic.content)
完整程序(可直接使用)
#-*-coding:utf8-*-
from lxml import etree
import requests
import re
def GetImgLink(url):
html = requests.get(url)
html = re.sub(r\'charset=(/w*)\', \'charset=UTF-8\', html.text)
ImgFilter = etree.HTML(html)
ImgLink = ImgFilter.xpath(\'//div[@class=\"l_post j_l_post l_post_bright \"]\')[0]
links = ImgLink.xpath(\'//div[@class=\"d_author\"]/ul/li/div[@class=\"icon_relative j_user_card\"]/a/img/@data-tb-lazyload\')
#links = ImgLink.xpath(\'//div[@class=\"d_author\"]/ul/li/div[@class=\"icon_relative j_user_card\"]/a/img/@src\')
print(links)
print(\"before set list:{0}\".format(len(links)))
links = list(set(links))
print(\"after set list:{0}\".format(len(links)))
i = 0
for each_link in links:
graphic = requests.get(each_link)
with open(\"img{0}.jpeg\".format(i),\"wb\") as code:
code.write(graphic.content)
i = i + 1
pagelink = \'http://tieba.baidu.com/p/3522395718?pn=1\'
GetImgLink(pagelink)
测试结果:
上一篇:微博爬虫
下一篇:SQLAlchemy入门(一)