Python3 网络爬虫(一) urllib模块
Python3 网络爬虫(二) 正则表达式 re模块
pip install beautifulsoup4
常用的解析器:”html.parser” “lxml” [“lxml”, “xml”](能够解析XML) “html5lib”
soup = BeautifulSoup(html, "html.parser")
Tag操作方式与dict()类似:Name,Attributes
soup = BeautifulSoup('Extremely bold')
tag = soup.b
type(tag)
# 'bs4.element.Tag'>
tag.name
# u'b'
tag['class'] # 多值属性返回列表
# u'boldest'
tag.attrs
# {u'class': u'boldest'}
tag.string
# u'Extremely bold'
find_all() 与 findAll() 方法用法相同效果相同
find_all(name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)
name 匹配Tags的名字,获得相应的结果集。
soup.find_all('b')
# [one, two]
tagsStartingWithB = soup.find_all(re.compile('^b'))
soup.find_all(['title', 'p'])
# [Page title ,
# This is paragraph one.
,
# This is paragraph two.
]
soup.find_all({'title' : True, 'p' : True})
# [Page title ,
# This is paragraph one.
,
# This is paragraph two.
]
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")
# ["firstpara" align="center">This is paragraph one.
]
soup.find_all(class_="center")
# ["firstpara" class="center">This is paragraph one.
]
# 也可以使用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