获取数据之后需要对数据进行解析和提取,需要用到的库是BeautifulSoup,需要在终端安装 pip install BeautifulSoup4
1)解析数据
bs对象=BeautifulSoup("要解析的文本","解析器")
解析器我们一般用Python的内置库:html.parser
示例:
import requests
from bs4 import BeautifulSoup
#引入BS库
res = requests.get('https://localprod.pandateacher.com/python-manuscript/crawler-html/spider-men5.0.html')
html = res.text
soup = BeautifulSoup(html,'html.parser') #把网页解析为BeautifulSoup对象
2)数据提取
需要用到BeautifulSoup中的两大知识点:find()和find_all();以及Tag对象
find()与find_all()是BeautifulSoup对象的两个方法,它们可以匹配html的标签和属性,把BeautifulSoup对象里符合要求的数据都提取出来。
它俩的用法基本是一样的,区别在于,find()只提取首个满足要求的数据,而find_all()提取出的是所有满足要求的数据。
括号中的参数:标签和属性可以任选其一,也可以两个一起使用,这取决于我们要在网页中提取的内容。
示例:
import requests
from bs4 import BeautifulSoup
res=requests.get('https://localprod.pandateacher.com/python-manuscript/crawler-html/spider-men5.0.html')
html=res.text
soup=BeautifulSoup(html,'html.parser')
items=soup.find_all(class_='books')
for item in items:
kind=item.find('h2')
title=item.find(class_='title')
brief=item.find(class_='info')
print(kind,'\n',title,'\n',brief)
print(type(kind),type(title),type(brief))
这时候得到的数据带有tag标签,属于tag类型的数据。如果想要得到纯文本数据,需要用到Tag对象。
Tag对象
我们用Tag.text提出Tag对象中的文字,用Tag['href']提取出URL。
这里只需修改上面例子的最后一行代码,改为
print(kind.text,'\n',title.text,'\n',title['href'],'\n',brief.text)
就可以得到文本数据。
汇总起来就是