Python爬虫beautifulsoup4常用的解析方法总结

yipeiwu_com6年前Python爬虫

摘要

  • 如何用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实现抓取网页并且解析的实例

本文以实例形式讲述了Python实现抓取网页并解析的功能。主要解析问答与百度的首页。分享给大家供大家参考之用。 主要功能代码如下: #!/usr/bin/python #coding...

python爬取酷狗音乐排行榜

本文为大家分享了python爬取酷狗音乐排行榜的具体代码,供大家参考,具体内容如下 #coding=utf-8 from pymongo import MongoClient im...

Python爬虫学习之翻译小程序

Python爬虫学习之翻译小程序

本次博客分享的内容为基于有道在线翻译实现一个实时翻译小程序,本次任务是参考小甲鱼的书《零基础入门学习Python》完成的,书中代码对于当前的有道词典并不适用,使用后无法实现翻译功能,在网...

python书籍信息爬虫实例

python书籍信息爬虫示例,供大家参考,具体内容如下 背景说明 需要收集一些书籍信息,以豆瓣书籍条目作为源,得到一些有效书籍信息,并保存到本地数据库。 获取书籍分类标签 具体可参考这个...

python爬虫使用cookie登录详解

python爬虫使用cookie登录详解

前言: 什么是cookie? Cookie,指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据(通常经过加密)。 比如说有些网站需要登录后才能访问某个...