Python爬虫beautifulsoup4常用的解析方法总结(新手必看)

今天小编就为大家分享一篇关于Python爬虫beautifulsoup4常用的解析方法总结,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
摘要

如何用beautifulsoup4解析各种情况的网页
beautifulsoup4的使用

关于beautifulsoup4,官网已经讲的很详细了,我这里就把一些常用的解析方法做个总结,方便查阅。

装载html文档

使用beautifulsoup的第一步是把html文档装载到beautifulsoup中,使其形成一个beautifulsoup对象。

import requests
from bs4 import BeautifulSoup
url = "http://new.qq.com/omn/20180705/20180705A0920X.html"
r = requests.get(url)
htmls = r.text
#print(htmls)
soup = BeautifulSoup(htmls, 'html.parser')

初始化BeautifulSoup类时,需要加入两个参数,第一个参数即是我们爬到html源码,第二个参数是html解析器,常用的有三个解析器,分别是”html.parser”,”lxml”,”html5lib”,官网推荐用lxml,因为效率高,当然需要pip install lxml一下。

当然这三种解析方式在某些情况解析得到的对象内容是不同的,比如对于标签不完整这一情况(p标签只有一半):

soup = BeautifulSoup("<a></p>", "html.parser")
# 只有起始标签的会自动补全,只有结束标签的灰自动忽略
# 结果为:<a></a>
soup = BeautifulSoup("<a></p>", "lxml")
#结果为:<html><body><a></a></body></html>
soup = BeautifulSoup("<a></p>", "html5lib")
# html5lib则出现一般的标签都会自动补全
# 结果为:<html><head></head><body><a><p></p></a></body></html>

使用

在使用中,我尽量按照我使用的频率介绍,毕竟为了查阅~

按照标签名称、id、class等信息获取某个标签

html = '<p class="title" id="p1"><b>The Dormouses story</b></p>'
soup = BeautifulSoup(html, 'lxml')
#根据class的名称获取p标签内的所有内容
soup.find(class_="title")
#或者
soup.find("p",class_="title" id = "p1")
#获取class为title的p标签的文本内容"The Dormouse's story"
soup.find(class_="title").get_text()
#获取文本内容时可以指定不同标签之间的分隔符,也可以选择是否去掉前后的空白。
soup = BeautifulSoup('<p class="title" id="p1"><b> The Dormouses story </b></p><p class="title" id="p1"><b>The Dormouses story</b></p>', "html5lib")
soup.find(class_="title").get_text("|", strip=True)
#结果为:The Dormouses story|The Dormouses story
#获取class为title的p标签的id
soup.find(class_="title").get("id")
#对class名称正则:
soup.find_all(class_=re.compile("tit"))
#recursive参数,recursive=False时,只find当前标签的第一级子标签的数据
soup = BeautifulSoup('<html><head><title>abc','lxml')
soup.html.find_all("title", recursive=False)

按照标签名称、id、class等信息获取多个标签

soup = BeautifulSoup('<p class="title" id="p1"><b> The like story </b></p><p class="title" id="p1"><b>The Dormouses story</b></p>', "html5lib")
#获取所有class为title的标签
for i in soup.find_all(class_="title"):
print(i.get_text())
#获取特定数量的class为title的标签
for i in soup.find_all(class_="title",limit = 2):
print(i.get_text())

按照标签的其他属性获取某个标签

html = '<a alog-action="qb-ask-uname" href="/usercent" rel="external nofollow" target="_blank">蜗牛宋</a>'
soup = BeautifulSoup(html, 'lxml')
# 获取"蜗牛宋",此时,该标签里既没有class也没有id,需要根据其属性来定义获取规则
author = soup.find('a',{"alog-action":"qb-ask-uname"}).get_text()
#或
author = soup.find(attrs={"alog-action": "qb-ask-uname"})

找前头和后头的标签

soup.find_all_previous("p")
soup.find_previous("p")
soup.find_all_next("p")
soup.find_next("p")

找父标签

soup.find_parents("div")
soup.find_parent("div")

css选择器

soup.select("title") #标签名
soup.select("html head title") #多级标签名
soup.select("p > a") #p内的所有a标签
soup.select("p > #link1") #P标签内,按id查标签
soup.select("#link1 ~ .sister") #查找相同class的兄弟节点
soup.select("#link1 + .sister")
soup.select(".sister") #按class名称查
soup.select("#sister") #按id名称查
soup.select('a[href="http://example.com/elsie" rel="external nofollow" ]') # 按标签的属性查
soup.select('a[href$="tillie"]')
soup.select_one(".sister")

注意几个可能出现的错误,可以用try捕获来防止爬虫进程

UnicodeEncodeError: ‘charmap’ codec can’t encode character u’\xfoo’ in position bar (或其它类型的 UnicodeEncodeError
需要转码

AttributeError: ‘NoneType’ object has no attribute ‘foo’
没这个属性
注意:很多人学Python过程中会遇到各种烦恼问题解决不了。为此小编建了个Python全栈免费答疑交流.裙 : 624440745不懂的问题有老司机解决里面还有最新Python教程项目可拿,,一起相互监督共同进步!
本文的文字及图片来源于网络加上自己的想法,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。

posted @ 2020-02-27 16:50  橙子CX  阅读(2259)  评论(0编辑  收藏  举报