美文网首页
《Python网络爬虫》3.1 BeautifulSoup库安装

《Python网络爬虫》3.1 BeautifulSoup库安装

作者: 一页编程 | 来源:发表于2017-04-09 17:01 被阅读0次

By 一页编程


Beautiful Soup parses anything you give it, and does the tree traversal stuff for you.

BeautifulSoup也叫美味汤,他是一个非常优秀的python第三方库,它能够对html、xml格式进行解析,并且提取其中的相关信息。在BeautifulSoup的网站上有这样一番话,BeautifulSoup可以对你提供给他的任何格式进行相关的爬取,并且可以进行树形解析。

BeautifulSoup的使用原理是它能够把任何你给它的文档当做一锅汤,然后给你煲制这锅汤。

安装BeautifulSoup

用管理员权限启动命令行,然后我们在命令行上执行如下命令:

pip install beautifulsoup4

测试页面

BeautifulSoup就下载安装完成了,然后我们对比BeautifulSoup来个小测。这里边我们使用一个html页面,
地址是http://www.yeahcoding.tech/python/demo.html 我们用浏览器先打开这个网站看一下。

在这个页面中我们看到它有一个标题栏,上面有一行字,叫this is a python demo,这个地方表示的是一个title信息,我们可以将这个文件存取下来,生成dem.html或者我们用它的源代码。


我们打开它的源代码,能看到这个页面对应的是一个html5格式的代码,在代码中我们看到了很多的标签,这种标签以一对尖括号来表示。

Requests库获取页面源码

我们已经学过了Requests库,可以用Requests库来自动的获得这个链接对应的源代码。

>>> import requests
>>> r = requests.get('http://www.yeahcoding.tech/python/demo.html')
>>> r.text
'\n<html><head><title>This is a python demo page</title></head>\n<body>\n<p class="title"><b>The demo python introduces several python courses.</b></p>\n<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\n<a href="http://www.jianshu.com/nb/11366912 class="py1" id="link1">Python Crawler</a> .</p>\n</body></html>'
>>> 

使用BeautifulSoup库

下面我来对beatifulsoup的安装进行小测。

>>> demo = r.text
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(demo, 'html.parser')
>>> print(soup.prettify)
<bound method Tag.prettify of 
<html><head><title>This is a python demo page</title></head>
<body>
<p class="title"><b>The demo python introduces several python courses.</b></p>
<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a href="http://www.jianshu.com/nb/11366912 class=" id="link1" py1"="">Python Crawler</a> .</p>
</body></html>>
>>> 

尽管我们安装这个库的时候安装的是beautifulsoup4,但是我们在使用的时候,我们可以用它的简写bs4,所以我们使用from bs4 import BeautifulSoup引入了BeautifulSoup类。

然后,我们把这个demo的页面熬成一个BeautifulSoup能够理解的汤。除了给出demo,同时还要给出一个解析demo的解释器,这里边我们的解释器使用的是html.parser,也就是说我们是对demo进行html的解析。

那下面我们看看我们解析是否正确,也就是看一下BeautifulSoup库安装是否正确,用Print语句将我们做的这锅汤打印出来。

总结

使用BeautifulSoup库简单来说只需要两行代码:

from bs4 import BeautifulSoup
soup = BeautifulSoup(‘<p>data</p>’)

BeautifulSoup类有两个参数,第一个参数是我们需要解析的一个HTML格式的信息,使用<p>data</p>表示;第二个参数是解析器,我们这里使用的html.parser

只有两个代码,我们就可以解析我们看到的html的信息,是不是很简单呢!

相关文章

网友评论

      本文标题:《Python网络爬虫》3.1 BeautifulSoup库安装

      本文链接:https://www.haomeiwen.com/subject/ueidattx.html