版权声明:本文为作者原创文章,可以随意转载,但必须在明确位置标明出处!!!
tips:本基础系列旨在以爬虫带大家入门Python语言
上一篇文章讲了使用 socket 原生套接字实现HTTP协议的工作流程。到这里 Python 语言的语法、用法都基本讲完,剩下的web、图形界面方面的知识不在本基础系类的讨论范围内,对 Python web 感兴趣的同学可以自行去学习一下flask、django这两个web开发框架,本章要讲的是 BeautifulSoup 库的使用,混了这么就的新人村了,也该出去打打猎了,打猎是需要装备的,BeautifulSoup 就是我们的打猎装备,暂且就叫屠龙刀好了。在正式打猎开始之前我们应该属性熟悉武器的属性之后才能让我们用的得心应手。
安装 Beautiful Soup
如何你是用的我第一篇文章讲到的基础环境,那么只需要在命令行终端执行下面的命令就可以了
sudo apt-get install Python-bs4
当然你也可以使用pip来安装也可以使用源码安装,几种方式都可以。
pip install beautifulsoup4
lxml解析器安装
光有 BeautifulSoup 还不行,还必须得有一个解析器,Python 标准库也自带了一个解析库html.parser,不过这个库没有lxml速度快,文档容错能力也没有lxml强。安装方式有几种
sudo apt-get install Python-lxml
pip install lxml
easy_install lxml
几种解析器的优缺点
BeautifulSoup的四中对象
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种: Tag , NavigableString , BeautifulSoup , Comment 。
Tag 对象
Tag的属性很熟,一个name属性和一个多值属性
from bs4 import BeautifulSoup
soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
tag = soup.b
print(tag.name) # u'b'
print(tag['class']) #boldest
print(tag.attrs) # {u'class': u'boldest'}
- 多值属性
from bs4 import BeautifulSoup
soup = BeautifulSoup('<b class="boldes strikeoutt">Extremely bold</b>')
tag = soup.b
print(tag['class']) # ["body", "strikeout"]
NavigableString对象
该对象表示一个字符串对象,若Tag的子节点中不包含其它Tag了,那么可以用string属性取到Tag包含的字符串,若Tag子节点中包含了其它Tag那么string属性将返回None
from bs4 import BeautifulSoup
soup = BeautifulSoup('<b class="boldes strikeoutt"><Extremely bold</b>')
soup1 = BeautifulSoup('<b class="boldes strikeoutt"><h1>Extremely bold</h1></b>')
tag = soup.b
tag1 = soup1.b
print(tag.string) # Extremely bold
print(tag1 .string) # None
Comment对象
该对象表示文档中的注释部分。
from bs4 import BeautifulSoup
markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>"
soup = BeautifulSoup(markup)
comment = soup.b.string
type(comment) # <class 'bs4.element.Comment'>
print(comment)
# u'Hey, buddy. Want to buy a used parser'
BeautifulSoup对象
BeautifulSoup对象表示的是一个文档的全部内容,所以当我们解析文档的时候首先要做的就是将文档实例化为BeautifulSoup对象,然后对其进行解析。BeautifulSoup对象包含了太多的属性和方法,方法值得注意的是find(),find_all()过滤,其它的属性就不一一讲了,下面给出一张思维导图帮助读者查阅,你也可以访问官方文档Beautiful Soup 4.4.0 文档查看每个属性的用法。
使用BeautifulSoup解析糗事百科
#!/usr/bin/env python
import urllib
from urllib import request
import re
from bs4 import BeautifulSoup
import bs4
import time
url = 'https://www.qiushibaike.com/'
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.691.400 QQBrowser/9.0.2524.400'
headers = {'User-Agent': user_agent}
try:
req = request.Request(url, headers=headers)
response = request.urlopen(req, timeout=2)
content = response.read().decode('utf-8')
soup = BeautifulSoup(content.replace('\n', ''), 'lxml')
for item in soup.find(id='content-left').children:
try:
if type(item) == bs4.element.Comment:
pass
print(type(item))
print(item.find(class_='content').span.text)
except Exception as e:
raise e
except Exception as e:
print(e)
okay,BeautifulSoup的介绍就到这里结束,想要明白它,最好的方法就是去使用它。
网友评论