BeautifulSoup是一个模块,该模块用于接收一个HTML或XML字符串,然后将其进行格式化,之后遍可以使用他提供的方法进行快速查找指定元素,从而使得在HTML或XML中查找指定元素变得简单。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse\'s story</title></head><body>asdf <div class="title">
<b>The Dormouse\'s story总共</b>
<h1>f</h1>
</div>
<div class="story">Once upon a time there were three little sisters; and their names were <a class="sister0" id="link1">Els<span>f</span>ie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</div>ad<br/>sf<p class="story">...</p></body></html>"""soup = BeautifulSoup(html_doc, features="lxml")
# 找到第一个a标签tag1 = soup.find(name=\'a\')
# 找到所有的a标签tag2 = soup.find_all(name=\'a\')
# 找到id=link2的标签tag3 = soup.select(\'#link2\')
|
再给大家举个经常用的例子:
一,这个参数需要一个字符串,response是一个对象,response.text是字符串,
二,’lxml‘是解析器,指定用lxmL做解析器
三,四,这两个合在一起,是找到类选择器为btnlinks的p标签
五,找出标签元素里href对应的url
注意:find得到的是第一个标签元素,find_all是得到的是一个列表,元素是所有的符合条件的标签,可以通过下标获取元素。