python爬虫—DAY3----xpath数据解析实战
4k图片解析爬取
需求: 爬取 http://pic.netbian.com/4kmeinv/ 中图片数据,并保存
分析:
代码
import requests
from lxml import etree
# os 用来创建文件夹保存爬取的图片
import os
url="https://pic.netbian.com/4kmeinv/"
headers={
"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67'
}
# 爬取页面数据。
page_text=requests.get(url=url,headers=headers).text
# 解析数据,拿到图片url
tree=etree.HTML(page_text)
#因为图片地址在li标签下,所有要先获取所有li标签
li_list=tree.xpath(r"//*[@id='main']/div[3]/ul/li")
# 创建文件夹存储图片
if not os.path.exists("./img_Libs"):
os.makedirs('./img_Libs')
#进行图片地址获取
for li in li_list:
#真正的图片的url如下,所以需要对爬取的图片进行拼接
#https://pic.netbian.com/uploads/allimg/210718/001826-16265387066216.jpg
img_url="https://pic.netbian.com"+li.xpath('./a/img/@src')[0]
#为图片名字加上后缀,方便电脑识别文件格式
img_name=li.xpath("./a/img/@alt")[0]+".jpg"
#由于网页是gbk编码,所以为了为了防止乱码,进行如下操作
img_name=img_name.encode("iso-8859-1").decode('gbk')
# 对获取到的图片url进行请求,注意图片,视频等为二进制数据,不使用.text,使用.content
img_content=requests.get(url=img_url,headers=headers).content
#进行持久话存储,二进制数据存储不用写第三个参数,且第二个参数为 'wb'
img_path='./img_Libs/'+img_name
with open(img_path,'wb') as fp:
fp.write(img_content)
print(img_name, "爬取成功")
三国演义爬取
需求:爬取 https://www.shicimingju.com/book/sanguoyanyi.html 中三国演义内容
分析:
爬取时发现文字是乱码,所以要进行处理。而内容不在同一页,所以要二次爬取
代码
import requests
from lxml import etree
url="https://www.shicimingju.com/book/sanguoyanyi.html"
headers={
"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67'
}
page_text=requests.get(url=url,headers=headers).text
# 对爬取到的内容进行处理,解决乱码
page_text=page_text.encode('iso-8859-1').decode('utf-8')
tree=etree.HTML(page_text)
li_list=tree.xpath('//*[@id="main_left"]/div/div[4]/ul/li')
# 打开一个文件,用于存储内容
fp=open("./三国演义.txt",'w',encoding="utf-8")
for li in li_list:
#提取出每个章节的名字
name=li.xpath("./a/text()")[0]
#https://www.shicimingju.com/book/sanguoyanyi/9.html
#对比真正的url,进行相应的拼接
detail_url="https://www.shicimingju.com"+li.xpath('./a/@href')[0]
#对内容再次发起请求,获取数据
detail_text=requests.get(url=detail_url,headers=headers).text
# 处理乱码
detail_text=detail_text.encode("iso-8859-1").decode('utf-8')
# 解析出章节内容,注意,该章节每段存储在一个元素中,所以用//text()提取出所有文本
tree_detail=etree.HTML(detail_text)
detail_content=tree_detail.xpath("//*[@id='main_left']/div[1]/div//text()")
chapter_content=""
# 因为返回的是一个列表,所以需要拼接每个段落。
for content in detail_content:
chapter_content+=content
chapter_content+="\n"
#写入存储
fp.write(name+":"+chapter_content+"\n")
如有错误,麻烦指正,感谢。