一、数据解析概述
聚焦爬虫:爬取页面中指定的页面内容。
- 编码流程:
- 指定url
- 发起请求
- 获取响应数据
- 数据解析
- 持久化存储
数据解析分类:
- 正则
- bs4
- xpath (***)
数据解析原理概述:
- 解析的局部的文本内容都会在标签之间或者标签对应的属性中进行存储
- 1.进行指定标签的定位
- 2.标签或者标签对应的属性中存储的数据值进行提取(解析)
二、三种数据解析的方法
1、正则解析:
实例:批量爬取http://photo.xitek.com/中的图片
正则表达式为:ex = '<div class="element".*?<img src="(.*?)".*?</div>'
![]()
1 if __name__ == '__main__':
2 headers = {
3 "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
4 }
5 if not os.path.exists("./靓图"):
6 os.mkdir("./靓图")
7 # url = "http://photo.xitek.com/"
8 url = 'http://photo.xitek.com/style/0/p/'
9 for page_num in range(1,4):
10 url = url + str(page_num)
11 # 通用爬虫 爬取整张页面
12 html = requests.get(url=url, headers=headers).text
13 # 聚焦爬虫 爬取图片链接
14 ex = '<div class="element".*?<img src="(.*?)".*?</div>'
15 img_list = re.findall(ex,html,re.S)
16 for img_url in img_list:
17 # content返回二进制类型的数据
18 # text 返回文本数据
19 # json() 返回json字典
20 response = requests.get(url=img_url,headers=headers).content
21
22 filename = "./靓图/"+img_url.split("/")[-1]
23 with open(filename,"wb") as f:
24 f.write(response)
25 print("第"+str(page_num)+"页已完成!")
批量爬取网页中的图片
2、bs4进行数据解析
数据解析的原理:
-1.标签定位
-2.提取标签、标签属性中存储的数据值
bs4数据解析的原理:
-1 实例化一个BeautifulSoup对象,并且将页面源码数据加载到该对象中
-2 通过调用BeautifulSoup对象中相关的属性或者方法进行标签定位和数据提取
需要安装:pip install bs4
bs4在使用时候需要—个第三方库,把这个库也安装一下
pip install lxml
如果下载失败,或下载速度极慢,建议把pip源改为国内源,阿里源、豆瓣源、网易源等
- windows
(1)打开文件资源管理器(文件夹地址栏中)
(2)地址栏上面输入%appdata%
(3)在这里面新建一个文件夹pip
(4)在pip文件夹里面新建一个文件叫做pip.ini,内容写如下即可
[global]
timeout = 6000
index-url = https://mirrors.aliyun.com/pypi/simple/
trusted-host = mirrors.aliyun.com
- Linux
(1) cd ~
(2) mkdir -/-pip
(3) vi -/ -pip/pip.conf
(4)编辑内容和windows—模—样
如何实例化一个BeautifulSoup对象呢?
# 导包
from bs4 import BeautifulSoup
1.将本地的html文档中的数据加载到该对象中
f = open("sogou.html","r",encoding="utf-8")
soup = BeautifulSoup(f, "lxml")
2.将互联网上获取的页面源码加载到该对象中
page_text = response.text
soup = BeautifulSoup(page_text, 'lxml')
3.soup的方法有哪些?
soup.Tagname,比如:soup.a soup.p
返回的是html中第一次出现的Tagname标签
soup.find():
find('div'):等同于soup.div
属性定位:
soup. find( 'div', class_/id/attr='song')
soup.find_all('tagName'):返回符合要求的所有标签(列表)
也可以进行数据定位
soup.select():
soup.select( '某种选择器(id, class,标签.. .选择器) ' ) ,返回的是个列表。
层级选择器:
soup.select(".tang > ul > li > a"): 大于号表示的是一个层级
soup.select(".tang > ul a"):空格表示的多个层级
4.获取标签之间的文本数据:
soup.a.text/string/get_text()
text/get_text():可以获取某一个标签中所有的文本内容(子子孙孙)
string:只可以获取该标签下面直系的文本内容(儿子)
5.获取标签中属性值:
soup.a["href"]
3、xpath解析:最常用且最便捷高效的一种解析方式。通用性。
xpath解析原理:
1.实例化一个et ree的对象,且需要将被解析的页面源码数据加载到该对象中。
2.调用etree对象中的xpath方法结合着xpath表达式实现标签的定位和内容的捕获。
环境的安装:
pip install lxml
如何实例化一个etree对象:from lxml import etree
1.将本地的html文档中的源码数据加载到etree对象中:
etree.parse(filePath)
2.可以将从互联网上获取的源码数据加载到该对象中
etree.HTML('page_text')
3.xpath("xpath表达式")
xpath表达式:
/: 表示的是从根节点开始定位。表示的是个层级。
//: 表示的是多个层级。可以表示从任意位置开始定位。
属性定位: //div[@class='song'] ——> tag[@att rName=" attrValue"]
索引定位: //div[@class="song"]/p[3] 索引是从1开始的。
取文本:
/text()获取的是标签中直系的文本内容
//text()标签中非直系的文本内容(所有的文本内容)
取属性:
/@attrName ==> img/@src
![]()
1 if __name__ == '__main__':
2 url = "https://ta.58.com/ershoufang/"
3 headers = {
4 "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
5 }
6 response = requests.get(url=url,headers=headers).text
7 tree = etree.HTML(response)
8 li_list = tree.xpath("//ul[@class='house-list-wrap']/li")
9 f = open("./58二手房.txt","w",encoding="utf-8")
10 for li in li_list:
11 title = li.xpath("./div[2]/h2/a/text()")[0]
12 price_list = li.xpath("./div[3]/p//text()")
13 tol_price = price_list[0]+price_list[1]
14 avg_price = price_list[2]
15 f.write(title+" / "+tol_price+" / "+avg_price+"\n")
Xpath案例1 58同城二手房信息
![]()
1 if __name__ == '__main__':
2 url = "http://pic.netbian.com/"
3 headers = {
4 "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
5 }
6 page_txt = requests.get(url=url,headers=headers).text
7 tree = etree.HTML(page_txt)
8 li_list = tree.xpath('//div[@class="slist"]/ul/li')
9 # 创建一个文件夹来保存图片
10 if not os.path.exists("./4k图片"):
11 os.mkdir("./4k图片")
12 for li in li_list:
13 img_url = "http://pic.netbian.com"+li.xpath(".//img/@src")[0]
14 img_name = li.xpath(".//img/@alt")[0] + ".jpg"
15 # 通用的解决中文乱码的方法
16 img_name = img_name.encode("iso-8859-1").decode("gbk").replace(" ","")
17 # print(img_url,img_name)
18 # 请求图片,进行持久化存储
19 img_content = requests.get(url=img_url,headers=headers).content
20 with open("./4k图片/"+img_name,"wb") as f:
21 f.write(img_content)
22 print(img_name+"下载完成!")
Xpath下载图片并解决中文乱码问题