-数据解析的原理:
-1.标签定位
-2.提取标签,标签属性中存储的数量的具体值
-bs4数据解析的原理:
-1.实例化一个【BeatifulSoup】对象,并且将页面源码数据加载到该对象中
-2.通过调用【BeatifulSoup】对象中相关的属性或者方法进行标签定位和数据提取
-环境安装:
-pip install bs4
-pip install lxml(解析器)
-如何实例化【BeatifulSoup】对象:
-from bs4 import BeautifulSoup
-对象的实例化
-1.将本地的html文档中的数据加载到该对象中
fp=open('./test.html','r',encoding='utf-8')
soup=BeautifulSoup(fp,'lxml')[报错将'lxmll'改成【soup = BeautifulSoup(fp, 'html.parser')】]
-2.将互联网上获取的页面源码加载到该对象中【☆使用多】
page_text=response.text
soup=BeatifulSoup(page_text,'lxml')
-提供的用于数据解析的方法和属性:
-soup.tagName 返回的是文档中第一次出现的tagName对应的标签
-soup.find():
-find('tagName'):等同于soup.div
-属性定位:
-soup.fin('div',class_/id/attr='song')[class是关键字,参数名称一定是class_]
-soup.find_all('tagName'):返回符合要求的所有标签,返回一个列表
-select:
-select('某种选择器(id,class,标签……选择器)'),返回的是一个列表。
-层级选择器:
-soup.select('.tang>ul>li>a'):>表示的是一个层级
-soup.select('.tang>ul a'): 空格表示多个层级
-获取标签之间的文本数据:
- suop.a.text/string/get_text()
-text/get_text():可以获取某一个标签中所有的文本内容
-string:只可以获取该标签下直系的文本内容
-获取标签中的属性:
-soup.a['href']
例题
from bs4 import BeautifulSoup
import requests
if __name__ == "__main__":
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome'
'/89.0.4389.90 Safari/537.36 Edg/89.0.774.63'}
url='https://www.shicimingju.com/book/sanguoyanyi.html'
page_text=requests.get(url=url,headers=headers).text.encode('ISO-8859-1')
#在首页中解析出章节的标题和详情页的url
#1.实例化BeautifulSoup对象,需要将页面激活码数据加载到该对象中
soup=BeautifulSoup(page_text,'html.parser')
li_list=soup.select('.book-mulu>ul>li')
fp=open('./sanguo.txt','w',encoding='utf-8')
for li in li_list:
title=li.a.string
detail_url='https://www.shicimingju.com'+li.a['href']
#对详情页进行请求,解析出章节内容
detail_page_text=requests.get(url=detail_url,headers=headers).text.encode('ISO-8859-1')
#解析出详情页中的相关的章节的内容
detail_soup=BeautifulSoup(detail_page_text,'html.parser')
div_tag=detail_soup.find('div',class_='chapter_content')
#解析到了章节的内容
content=div_tag.text
fp.write(title+':'+content+'\n')
print(title,'over!')
错误:【object of type ‘Response’ has no len()】响应对象没有长度
解决:在响应数据后加text
出现乱码:【  开平å
ƒå¹´æ£æœˆä¸äº¥ï¼Œå¸å›žè】
在每次响应数据后加.encode(‘ISO-8859-1’)
xpath解析:最常用且最便捷高效的一种解析方式
-xpath解析原理:
-1.实例化一个etree的对象,且需要将被解析的页面源码数据加载到该对象中。
-2.调用stree对象中的xpath方法结合着xpath表达式实现的标签的定位和内容的捕获
-环境的安装:
-pip install lxml
-如何实例化一个etree对象
-1.将本地的html文档中的源码数据加载到etree对象中:
etree.parse(filePath)
-2.可以将从互联网上获取的数据加载到该对象中:
etree.HTML('page_text')
-xpath('xpath表达式')
-xpath表达式:
-/:表示的是从根节点开始定位。表示的是一个层级。
-//:表示的是多个层级。可以表示从任意位置开始定位。
-属性定位://div[@class='song'] tag[@attrName="attrValue"]
-索引定位://div[@class='song'] tag/p[3]索引是从1开始的。
-取文本:
-/text() 获取的是标签中直系的文本内容
-//text() 标签中非直系的文本内容(所有的文本内容)
-取属性:
/@attrName ==>img/src
#那页面源代码
#提取和解析数据
from lxml import etree
import requests
if __name__ == "__main__":
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome'
'/89.0.4389.90 Safari/537.36 Edg/89.0.774.63'}
url='https://taian.zbj.com/search/f/?type=new&kw=python'
page_text=requests.get(url=url,headers=headers).text
html=etree.HTML(page_text)
divs=html.xpath('/html/body/div[6]/div/div/div[2]/div[4]')
for div in divs:
price=div.xpath('./div/div/div[2]/div[2]/i/text()')
title=div.xpath('./div/div/div[2]/div[3]/a/text()')
print(title)
from lxml import etree
import requests
import os
#解析下载图片数据
if __name__ == "__main__":
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome'
'/89.0.4389.90 Safari/537.36 Edg/89.0.774.63'}
#爬取页面源码数据
url='https://pic.netbian.com/4kmeishi/'
response=requests.get(url=url,headers=headers)
#手动设置响应数据的编码格式 response.encoding='utf-8'
#数据解析:src的属性值 解析alt属性
page_text=response.text
tree=etree.HTML(page_text)
li_list=tree.xpath('//div[@class="slist"]/ul/li')
if not os.path.exists('./picLibs'):
os.mkdir('./picLibs')
for li in li_list:
img_src='https://pic.netbian.com'+li.xpath('./a/img/@src')[0]
img_name=li.xpath('./a/img/@alt')[0]+'.jpg'
#通用处理中文乱码的解决方案
img_name=img_name.encode('iso-8859-1').decode('gbk')
#请求图片进行持久化存储
img_data=requests.get(url=img_src,headers=headers).content
img_path='picLibs/'+img_name
with open(img_path,'wb') as fp:
fp.write(img_data)
print(img_name,"over")
错误:【 Opening and ending tag mismatch】
使用 DOMParser 解析XML时,要求所有的标签必须闭合。有开始标签< >,就要有对应的结束标签(</>)。或者,标签是自闭和的(< />)。
错误:【lxml.etree.XPathEvalError: Invalid predicate】
请检查xpath路径打对了没有
#通用处理中文乱码的解决方案:
1.在每次响应数据后加.encode(‘ISO-8859-1’)
2.手动设置响应数据的编码格式 response.encoding=‘utf-8’
from lxml import etree
import requests
import os
#解析下载图片数据
if __name__ == "__main__":
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome'
'/89.0.4389.90 Safari/537.36 Edg/89.0.774.63'}
#全国城市的名称
url='https://www.aqistudy.cn/historydata/'
page_text=requests.get(url=url,headers=headers).text
tree=etree.HTML(page_text)
host_li_list=tree.xpath('//div[@class="buttom"]/ul/li')
all_city_names=[]
for li in host_li_list:
hot_city_name=li.xpath('./a/text()')[0]
all_city_names.append(hot_city_name)
#解析的是全部城市的名称
city_names_list=tree.xpath('//div[@class="bottom"]/ul/div[2]/li')
for li in city_names_list:
city_name=li.xpath('./a/text()')[0]
all_city_names.append(city_name)
print(all_city_names,len(all_city_names))