python爬虫之Beautiful Soup的基本使用
1、简介
简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释如下:
Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。
Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。
Beautiful Soup已成为和lxml、html6lib一样出色的python解释器,为用户灵活地提供不同的解析策略或强劲的速度。
2、环境安装
Beautiful Soup 3 目前已经停止开发,推荐在现在的项目中使用Beautiful Soup 4,不过它已经被移植到BS4了,也就是说导入时我们需要 from bs4 import BeautifulSoup 。所以这里我们用的版本是 Beautiful Soup 4.3.2 (简称BS4)。
1、快速安装
- pip install beautifulsoup4
2、如果想安装最新的版本,请直接下载安装包来手动安装,也是十分方便的方法
1、Beautiful Soup3.2.1
https://pypi.python.org/pypi/BeautifulSoup/3.2.1
2、Beautiful Soup4.3.2
https://pypi.python.org/pypi/beautifulsoup4/
下载完成之后解压
运行下面的命令即可完成安装
python setup.py install
3、然后需要安装 lxml
pip install lxml
另一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同,可以选择下列方法来安装html5lib:
pip install html5lib
Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快,推荐安装。
3、使用
官方文档:http://beautifulsoup.readthedocs.io/zh_CN/latest/
1、导入
- from bs4 import BeautifulSoup
2、我们首先创建一个html文件,为了模拟下面的操作。
- html = """
- <html><head><title>The Dormouse's story</title></head>
- <body>
- <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
- <p class="story">Once upon a time there were three little sisters; and their names were
- <a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></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.</p>
- <p class="story">...</p>
- """
3、创建 beautifulsoup 对象
- soup = BeautifulSoup(html)
另外,我们还可以打开本地的html文件。
- soup = BeautifulSoup(open('index.html'))
4、格式化输入
- soup = BeautifulSoup(html,"lxml")
- print(soup.prettify())
输出:
- <html>
- <head>
- <title>
- The Dormouse's story
- </title>
- </head>
这个很有用的哦,如果我们要分析本地的html文件没有格式化输出的时候,看起来就非常乱了,所以我们需要格式化输入后我们就能一目了然这个html文件的结构。
5、四大对象种类
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种
(1)Tag
(2)NavigableString
(3)BeautifulSoup
(4)Comment
(1)Tag
tag是什么鬼,tag中文意思是标签的意思,学过html的同学肯定明白,标签例如<a href="https://www.baidu.com">my name a</a>
感受一下tag的用法
- print(soup.title)
- #<title>The Dormouse's story</title>
- print(soup.head)
- #<head><title>The Dormouse's story</title></head>
细心的同学会发现,我有很多p标签,但是只能打印到从上往下的第一个匹配到的标签
- print(soup.p)
- #<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
- print(soup.a)
- #<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
- soup = BeautifulSoup(html,"lxml")
- print(soup.p)
- #<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
tag还有两个常用的属性,name和attrs
name:
- soup = BeautifulSoup(html,"lxml")
- print(soup.name)
- print(soup.head.name)
- #[document]
- #head
attrs:
- soup = BeautifulSoup(html,"lxml")
- print(soup.p.attrs)
- #{'name': 'dromouse', 'class': ['title']}
获取属性值的两种不同方法:
- soup = BeautifulSoup(html,"lxml")
- print(soup.p.attrs)
- print(soup.p.get("class"))
- print(soup.p["class"])
- #{'class': ['title'], 'name': 'dromouse'}
- #['title']
- #['title']
可以获取,当然也可以修改和删除
修改:
- soup = BeautifulSoup(html,"lxml")
- print(soup.p)
- soup.p["class"]="newclass"
- print(soup.p)
- #<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
- #<p class="newclass" name="dromouse"><b>The Dormouse's story</b></p>
删除:
- soup = BeautifulSoup(html,"lxml")
- print(soup.p)
- del soup.p["class"]
- print(soup.p)
- #<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
- #<p name="dromouse"><b>The Dormouse's story</b></p>
(2)NavigableString
1、我们已经通过tag方法找到标签,但是如果想找某个标签的内容怎么办。
- soup = BeautifulSoup(html,"lxml")
- print(soup.p.string)
- #The Dormouse's story
(3)BeautifulSoup
对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性。
- soup = BeautifulSoup(html,"lxml")
- print(type(soup.name))
- print(soup.name)
- print(soup.attrs)
- #<class 'str'>
- #[document]
- #{}
(4)Comment
Comment 对象是一个特殊类型的 NavigableString 对象,其实输出的内容仍然不包括注释符号,但是如果不好好处理它,可能会对我们的文本处理造成意想不到的麻烦。
- soup = BeautifulSoup(html,"lxml")
- print(soup.a)
- print(soup.a.string)
- print(type(soup.a.string))
- #<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
- #Elsie
- #<class 'bs4.element.Comment'>
a 标签里的内容实际上是注释,但是如果我们利用 .string 来输出它的内容,我们发现它已经把注释符号去掉了,所以这可能会给我们带来不必要的麻烦。
另外我们打印输出下它的类型,发现它是一个 Comment 类型,所以,我们在使用前最好做一下判断,判断代码如下
- import bs4
- soup = BeautifulSoup(html,"lxml")
- if type(soup.a.string)==bs4.element.Comment:
- print(soup.a.string)
(6)遍历文档树
contents和children的区别
1、contents
tag 的 .content 属性可以将tag的子节点以列表的方式输出
- soup = BeautifulSoup(html,"lxml")
- print(soup.p.contents)
- #[<b>The Dormouse's story</b>]
列表的话我们就可以通过下标取里面值
- soup = BeautifulSoup(html,"lxml")
- print(soup.p.contents[0])
- #<b>The Dormouse's story</b>
2、children
它返回的不是一个 list,不过我们可以通过遍历获取所有子节点。
我们打印输出 .children 看一下,可以发现它是一个 list 生成器对象
- soup = BeautifulSoup(html,"lxml")
- print(soup.p.children)
- #<list_iterator object at 0x01BAE310>
list可以通过for循环遍历取值
- soup = BeautifulSoup(html,"lxml")
- print(soup.p.children)
- for line in soup.p.children:
- print(line)
3、所有子孙节点(.descendants)
- .contents 和 .children 属性仅包含tag的直接子节点.例如,<head>标签只有一个直接子节点<title>
.descendants
- soup = BeautifulSoup(html,"lxml")
- for line in soup.descendants:
- print(line)
children和contents只会把html文件打印一遍,只是children需要用for循环遍历一下而已,但是descendantes会把html中每一个tag都遍历一遍的前提是子子孙孙都会遍历一下(有些朋友可能还是有点不明白,直接上代码你就懂了)
- <html><head><title>The Dormouse's story</title></head>
- <body>
- <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
- <p class="story">Once upon a time there were three little sisters; and their names were
- <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
- <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
- <a class="sister" href="http://example.com/tillie" id="link3">Tillie<span>Test<a>TEST</a></span></a>;
- and they lived at the bottom of a well.</p>
- <p class="story">...</p>
- </body></html>
- <head><title>The Dormouse's story</title></head>
- <title>The Dormouse's story</title>
- The Dormouse's story
- <body>
- <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
- <p class="story">Once upon a time there were three little sisters; and their names were
- <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
- <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
- <a class="sister" href="http://example.com/tillie" id="link3">Tillie<span>Test<a>TEST</a></span></a>;
- and they lived at the bottom of a well.</p>
- <p class="story">...</p>
- </body>
- <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
- <b>The Dormouse's story</b>
- The Dormouse's story
- <p class="story">Once upon a time there were three little sisters; and their names were
- <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
- <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
- <a class="sister" href="http://example.com/tillie" id="link3">Tillie<span>Test<a>TEST</a></span></a>;
- and they lived at the bottom of a well.</p>
- Once upon a time there were three little sisters; and their names were
- <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
- Elsie
- ,
- <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
- Lacie
- and
- <a class="sister" href="http://example.com/tillie" id="link3">Tillie<span>Test<a>TEST</a></span></a>
- Tillie
- <span>Test<a>TEST</a></span>
- Test
- <a>TEST</a>
- TEST
- ;
- and they lived at the bottom of a well.
- <p class="story">...</p>
- ...
descendants
4、节点内容(string)
通俗点说就是:如果一个标签里面没有标签了,那么 .string 就会返回标签里面的内容。如果标签里面只有唯一的一个标签了,那么 .string 也会返回最里面的内容(如果标签里面有很多很多的内容,它就不知道该找谁了,结果返回一个None)
- soup = BeautifulSoup(html,"lxml")
- print(soup.head.string)
- print(soup.title.string)
- #The Dormouse's story
- #The Dormouse's story
如果标签下有很多的内容,返回的就是None了
- soup = BeautifulSoup(html,"lxml")
- print(soup.html.string)
- #None
可能有些同学会说,没关系啊,内容多了你可以用for循环遍历一下不就成了么,那我们来试试。
结果:报错了
还可以这么说,比如,你找到了一个a标签,但是这个a标签有自己的内容,a标签下面还有一个a标签或者别的标签,这个a标签也有自己的内容,这个时候你要是用string的话肯定是None。
- soup = BeautifulSoup(html,"lxml")
- for line in soup.html.string:
- print(line)
- #TypeError: 'NoneType' object is not iterable
5、多个内容
.strings .stripped_strings
strings
获取多个内容,不过需要遍历获取,比如下面的例子
- soup = BeautifulSoup(html,"lxml")
- for line in soup.strings:
- print(repr(line))
- "The Dormouse's story"
- '\n'
- '\n'
- "The Dormouse's story"
- '\n'
- 'Once upon a time there were three little sisters; and their names were\n'
- ',\n'
- 'Lacie'
- ' and\n'
- 'Tillie'
- 'Test'
- 'TEST'
- ';\nand they lived at the bottom of a well.'
- '\n'
- '...'
- '\n'
结果
stripped_strings
输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容
- soup = BeautifulSoup(html,"lxml")
- for line in soup.stripped_strings:
- print(repr(line))
- "The Dormouse's story"
- "The Dormouse's story"
- 'Once upon a time there were three little sisters; and their names were'
- ','
- 'Lacie'
- 'and'
- 'Tillie'
- 'Test'
- 'TEST'
- ';\nand they lived at the bottom of a well.'
- '...'
结果
6、父节点
.parent 属性
其实就是把当前要找的标签的上一级标签打印出来(注意,会把上一级标签的所有子标签都打印回来)
例一:
- soup = BeautifulSoup(html,"lxml")
- print(soup.title.parent)
- #<head><title>The Dormouse's story</title></head>
例二:
- soup = BeautifulSoup(html,"lxml")
- print(soup.p.parent)
结果:
- <body>
- <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
- <p class="story">Once upon a time there were three little sisters; and their names were
- <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
- <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
- <a class="sister" href="http://example.com/tillie" id="link3">Tillie<span>Test<a>TEST</a></span></a>;
- and they lived at the bottom of a well.</p>
- <p class="story">...</p>
- </body>
7、全部父节点
.parents 属性
- soup = BeautifulSoup(html,"lxml")
- content = soup.head.title.string
- for parent in content.parents:
- print(parent.name)
结果你会发现,parents是递归查找到你指定标签的父标签名字,指定标签的爷爷标签,太爷爷标签,就这么一直找下去。(如果你想看一下你找到这个标签是具体在什么位置,可以这么找)
- title
- head
- html
- [document]
8、兄弟标签
.next_sibling .previous_sibling 属性
兄弟节点可以理解为和本节点处在统一级的节点,.next_sibling 属性获取了该节点的下一个兄弟节点,.previous_sibling 则与之相反,如果节点不存在,则返回 None
注意:实际文档中的tag的 .next_sibling 和 .previous_sibling 属性通常是字符串或空白,因为空白或者换行也可以被视作一个节点,所以得到的结果可能是空白或者换行
1、next_sibling
- soup = BeautifulSoup(html,"lxml")
- print(soup.p.next_sibling.next_sibling)
- <p class="story">Once upon a time there were three little sisters; and their names were
- <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
- <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
- <a class="sister" href="http://example.com/tillie" id="link3">Tillie<span>Test<a>TEST</a></span></a>;
- and they lived at the bottom of a well.</p>
结果
2、previous_sibling
- soup = BeautifulSoup(html,"lxml")
- print(soup.p.previous_sibling.previous_sibling)
#None
9、全部兄弟节点
.next_siblings .previous_siblings 属性
1、next_siblings
打印了初当前标签的所有子标签。(可以找form表单)
- soup = BeautifulSoup(html,"lxml")
- for a in soup.a.next_siblings:
- print(a)
结果:
- ,
- <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
- and
- <a class="sister" href="http://example.com/tillie" id="link3">Tillie<span>Test<a>TEST</a></span></a>
- ;
- and they lived at the bottom of a well.
10、前后节点
.next_element .previous_element 属性
与 .next_sibling .previous_sibling 不同,它并不是针对于兄弟节点,而是在所有节点,不分层次
注意:我们说的前一个或者下一个其实除了标签外标签内的内容其实也是一个属性
1、next_element(后)
- soup = BeautifulSoup(html,"lxml")
- print(soup.p.next_element )
- #<b>The Dormouse's story</b>
2、.previous_sibling(前)
html中第一个a标签的前一个标签的是html中第二个p标签(这个p标签的兄弟姐妹,不是所有)
- soup = BeautifulSoup(html,"lxml")
- print(soup.a.previous_sibling )
- #Once upon a time there were three little sisters; and their names were
11、搜索文档树
1、find_all( name , attrs , recursive , text , **kwargs )
find_all() 方法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件
1)name 参数
name参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略
A)传个字符串看看以列表的形式找出所有a标签
- soup = BeautifulSoup(html,"lxml")
- print(soup.find_all('a') )
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
B)正则表达式
如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容.下面例子中找出所有以b开头的标签,这表示<body>和<b>标签都应该被找到
- soup = BeautifulSoup(html,"lxml")
- print(soup.find_all(re.compile('^a')) )
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
C)传个列表看看
- soup = BeautifulSoup(html,"lxml")
- print(soup.find_all(['a','p']) )
结果:
- [<p class="title" name="dromouse"><b>The Dormouse's story</b></p>, <p class="story">Once upon a time there were three little sisters; and their names were
- <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
- <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
- <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
- and they lived at the bottom of a well.</p>, <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>, <p class="story">...</p>]
D)传 True
如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数 [4] ,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False
下面方法校验了当前元素,如果包含 class 属性却不包含 id 属性,那么将返回 True:
- def has_class_but_no_id(tag):
- return tag.has_attr('class') and not tag.has_attr('id')
将这个方法作为参数传入 find_all() 方法,将得到所有<p>标签:
- [<p class="title" name="dromouse"><b>The Dormouse's story</b></p>, <p class="story">Once upon a time there were three little sisters; and their names were
- <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
- <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
- <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
- and they lived at the bottom of a well.</p>, <p class="story">...</p>]
2、keyword 参数
注意:如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为 id 的参数,Beautiful Soup会搜索每个tag的”id”属性
- soup = BeautifulSoup(html,"lxml")
- print(soup.find_all(id='link2'))
- #[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
上正则表达式
- soup = BeautifulSoup(html,"lxml")
- print(soup.find_all(href=re.compile('elsie')))
- # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
还可以同时传多个属性参数进行进准查找
- soup = BeautifulSoup(html,"lxml")
- print(soup.find_all(href=re.compile("elsie"), id='link1'))
- # [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]
在这里我们想用 class 过滤,不过 class 是 python 的关键词,这怎么办?加个下划线就可以
- soup = BeautifulSoup(html,"lxml")
- print(soup.find_all("a", class_="sister"))
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性
- data_soup = BeautifulSoup('<div data-foo="value">foo!</div>')
- data_soup.find_all(data-foo="value")
- # SyntaxError: keyword can't be an expression
3、text参数
- soup = BeautifulSoup(html,"lxml")
- print(soup.find_all(text=" Elsie "))
- # [' Elsie ']
- print(soup.find_all(text=["Tillie", " Elsie ", "Lacie"]))
- #[' Elsie ', 'Lacie', 'Tillie']
- print(soup.find_all(text=re.compile("Dormouse")))
- #["The Dormouse's story", "The Dormouse's story"]
4、limit参数
find_all() 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果.
文档树中有3个tag符合搜索条件,但结果只返回了2个,因为我们限制了返回数量
- soup = BeautifulSoup(html,"lxml")
- print(soup.find_all('a',limit=2))
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
5、recursive 参数
- soup = BeautifulSoup(html,"lxml")
- print(soup.find_all('p'))
- print(soup.find_all('p',recursive=False))
- [<p class="title" name="dromouse"><b>The Dormouse's story</b></p>, <p class="story">Once upon a time there were three little sisters; and their names were
- <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
- <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
- <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
- and they lived at the bottom of a well.</p>, <p class="story">...</p>]
- []
6、一大波find操作
1、find( name , attrs , recursive , text , **kwargs )
它与 find_all() 方法唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果
- soup = BeautifulSoup(html,"lxml")
- print(soup.find_all('a'))
- print(soup.find('a'))
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
- #<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
2、find_next_siblings() find_next_sibling()
这2个方法通过 .next_siblings 属性对当 tag 的所有后面解析的兄弟 tag 节点进行迭代, find_next_siblings() 方法返回所有符合条件的后面的兄弟节点,find_next_sibling() 只返回符合条件的后面的第一个tag节点
3、find_previous_siblings() find_previous_sibling()
这2个方法通过 .previous_siblings 属性对当前 tag 的前面解析的兄弟 tag 节点进行迭代, find_previous_siblings()方法返回所有符合条件的前面的兄弟节点, find_previous_sibling() 方法返回第一个符合条件的前面的兄弟节点
4、find_all_next() find_next()
这2个方法通过 .next_elements 属性对当前 tag 的之后的 tag 和字符串进行迭代, find_all_next() 方法返回所有符合条件的节点, find_next() 方法返回第一个符合条件的节点
5、find_all_previous() 和 find_previous()
这2个方法通过 .previous_elements 属性对当前节点前面的 tag 和字符串进行迭代, find_all_previous() 方法返回所有符合条件的节点, find_previous()方法返回第一个符合条件的节点
注:以上(2)(3)(4)(5)(6)(7)方法参数用法与 find_all() 完全相同,原理均类似,在此不再赘
12、CSS选择器
我们在写 CSS 时,标签名不加任何修饰,类名前加点,id名前加 #,在这里我们也可以利用类似的方法来筛选元素,用到的方法是 soup.select(),返回类型是 list
(1)通过标签名查找
- soup = BeautifulSoup(html,"lxml")
- print(soup.select('title'))
- #[<title>The Dormouse's story</title>]
- soup = BeautifulSoup(html,"lxml")
- print(soup.select('a'))
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
- soup = BeautifulSoup(html,"lxml")
- print(soup.select('b'))
- #[<b>The Dormouse's story</b>]
(2)通过类名查找
- soup = BeautifulSoup(html,"lxml")
- print(soup.select('.sister'))
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
(3)通过 id 名查找
- soup = BeautifulSoup(html,"lxml")
- print(soup.select('#link1'))
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
(4)组合查找
组合查找即和写 class 文件时,标签名与类名、id名进行的组合原理是一样的,例如查找 p 标签中,id 等于 link1的内容,二者需要用空格分开
- soup = BeautifulSoup(html,"lxml")
- print(soup.select('p #link1'))
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
(5)属性查找
查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。
- soup = BeautifulSoup(html,"lxml")
- print(soup.select('a[class="sister"]'))
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
- soup = BeautifulSoup(html,"lxml")
- print(soup.select('a[href="http://example.com/elsie"]'))
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
同样,属性仍然可以与上述查找方式组合,不在同一节点的空格隔开,同一节点的不加空格
- soup = BeautifulSoup(html,"lxml")
- print(soup.select('p a[href="http://example.com/elsie"]'))
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
以上的 select 方法返回的结果都是列表形式,可以遍历形式输出,然后用 get_text() 方法来获取它的内容。
- soup = BeautifulSoup(html, 'lxml')
- print(type(soup.select('title')))
- #<class 'list'>
- print(soup.select('title')[0].get_text())
- #The Dormouse's story
- for title in soup.select('title'):
- print(title.get_text())
- #The Dormouse's story
转载:静觅 » Python爬虫利器二之Beautiful Soup的用法
python爬虫之Beautiful Soup的基本使用的更多相关文章
- Python爬虫之Beautiful Soup解析库的使用(五)
Python爬虫之Beautiful Soup解析库的使用 Beautiful Soup-介绍 Python第三方库,用于从HTML或XML中提取数据官方:http://www.crummv.com/ ...
- python 爬虫利器 Beautiful Soup
python 爬虫利器 Beautiful Soup Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文 ...
- [Python爬虫] 使用 Beautiful Soup 4 快速爬取所需的网页信息
[Python爬虫] 使用 Beautiful Soup 4 快速爬取所需的网页信息 2018-07-21 23:53:02 larger5 阅读数 4123更多 分类专栏: 网络爬虫 版权声明: ...
- python爬虫之Beautiful Soup基础知识+实例
python爬虫之Beautiful Soup基础知识 Beautiful Soup是一个可以从HTML或XML文件中提取数据的python库.它能通过你喜欢的转换器实现惯用的文档导航,查找,修改文档 ...
- Python爬虫库-Beautiful Soup的使用
Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库,简单来说,它能将HTML的标签文件解析成树形结构,然后方便地获取到指定标签的对应属性. 如在上一篇文章通过爬虫 ...
- python 爬虫5 Beautiful Soup的用法
1.创建 Beautiful Soup 对象 from bs4 import BeautifulSoup html = """ <html><head& ...
- Python爬虫之Beautiful Soup库的基本使用
- [转]python下很帅气的爬虫包 - Beautiful Soup 示例
原文地址http://blog.csdn.net/watsy/article/details/14161201 先发一下官方文档地址.http://www.crummy.com/software/Be ...
- python下很帅气的爬虫包 - Beautiful Soup 示例
先发一下官方文档地址.http://www.crummy.com/software/BeautifulSoup/bs4/doc/ 建议有时间可以看一下python包的文档. Beautiful Sou ...
随机推荐
- pandas 选择列或者添加列生成新的DataFrame
选择某些列 import pandas as pd # 从Excel中读取数据,生成DataFrame数据 # 导入Excel路径和sheet name df = pd.read_excel(exce ...
- CPU, PSU, SPU - Oracle Critical Patch Update Terminology Update
It all started in January 2005 with Critical Patch Updates (CPU). Then Patch Set Updates (PSU) were ...
- oracle 乘积的实现方法
with abc(col1) as ( ' from dual union all ' from dual union all ' from dual ) select col1,ln(col1),e ...
- Java中class的getName()和getCanonicalName()两个方法的区别
getName()返回的是虚拟机里面的class的表示 getCanonicalName()返回的是更容易理解的表示 对于普通类来说,二者没什么区别,只是对于特殊的类型上有点表示差异 比如byte[] ...
- XSS高级利用
XSS会话劫持 (1)Cookie简介 Cookie是能够让网站服务器把少量文本数据存储到客户端的硬盘.内存,或者是从客户端的硬盘.内存读取数据的一种技术. Cookie是一段随HTTP请求.响应一起 ...
- P1440 求m区间内的最小值--洛谷luogu
题目描述 一个含有n项的数列(n<=2000000),求出每一项前的m个数到它这个区间内的最小值.若前面的数不足m项则从第1个数开始,若前面没有数则输出0. 输入输出格式 输入格式: 第一行两个 ...
- 20175310 MyCP(课下作业,必做)
一.作业要求 编写MyCP.java 实现类似Linux下cp XXX1 XXX2的功能,要求MyCP支持两个参数: java MyCP -tx XXX1.txt XXX2.bin 用来把文本文件(内 ...
- MySQL报错: java.sql.SQLException: Column count doesn't match value count at row 1
这个是今天写新项目的是后,写插入语句测试用例的时候报这个错误, 其实错误的原因就是插入语句的前面的列和后面的值 的个数不对. 错在此,仔细检查一下,看看少了哪一个,然后修改就可以了.
- python内置的高效好用各种库
二分查找,import bisect 堆排序,import heapq 哈希算法,import hashlib 压缩,lzma 图形处理,PIL 处理xml文件,PyXML 多媒体操作,PyMedia ...
- lambda从入门到精通
JDK8中包含了许多内建的Java中常用到函数接口,比如Comparator或者Runnable接口,这些接口都增加了@FunctionalInterface注解以便能用在lambda上. name ...