Python3 网络爬虫(三) 页面解析 BeautifulSoup模块

Python3 网络爬虫(一) urllib模块

Python3 网络爬虫(二) 正则表达式 re模块


安装

pip install beautifulsoup4

解析器

常用的解析器:”html.parser” “lxml” [“lxml”, “xml”](能够解析XML) “html5lib”

soup = BeautifulSoup(html, "html.parser")

bs4对象

Tag操作方式与dict()类似:Name,Attributes

soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
tag = soup.b
type(tag)
# <class 'bs4.element.Tag'>

tag.name
# u'b'
tag['class'] # 多值属性返回列表
# u'boldest'
tag.attrs
# {u'class': u'boldest'}
tag.string
# u'Extremely bold'

解析网页基本的方法find_all()

find_all() 与 findAll() 方法用法相同效果相同

find_all(name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)

name 匹配Tags的名字,获得相应的结果集。

soup.find_all('b')
# [<b>one</b>, <b>two</b>]
tagsStartingWithB = soup.find_all(re.compile('^b'))
soup.find_all(['title', 'p'])
# [<title>Page title</title>, 
#  <p id="firstpara" align="center">This is paragraph <b>one</b>.</p>, 
#  <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>]

soup.find_all({'title' : True, 'p' : True})
# [<title>Page title</title>, 
#  <p id="firstpara" align="center">This is paragraph <b>one</b>.</p>, 
#  <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>]

allTags = soup.find_all(True)
[tag.name for tag in allTags]
[u'html', u'head', u'title', u'body', u'p', u'b', u'p', u'b']

keyword参数用于筛选tag的属性。

soup.find_all(align="center")
# [<p id="firstpara" align="center">This is paragraph <b>one</b>.</p>]
soup.find_all(class_="center")
# [<p id="firstpara" class="center">This is paragraph <b>one</b>.</p>]
# 也可以使用sttrs={"class":"center"}方法

text 是一个用于搜索NavigableString对象的参数,recursive表示只查找当前子标签还是解析对象

soup.find_all(text="one")
# [u'one']
soup.find_all(text=lambda(x): len(x) < 12)
# [u'Page title', u'one', u'.', u'two', u'.']
[tag.name for tag in soup.html.find_all()]
# [u'head', u'title', u'body', u'p', u'b', u'p', u'b']
[tag.name for tag in soup.html.find_all(recursive=False)]
# [u'head', u'body']

limit参数为限定个数匹配。

Reference:
https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值