beautifulsoup(beautifulsoup库怎么安装)

admin 438 0

大家好,今天小编来为大家解答以下的问题,关于beautifulsoup,beautifulsoup库怎么安装这个很多人还不知道,现在让我们一起来看看吧!

一、如何提取正文内容 BeautifulSoup的输出

创建一个新网站,一开始没有内容,通常需要抓取其他人的网页内容,一般的操作步骤如下:

根据url下载网页内容,针对每个网页的html结构特征,利用正则表达式,或者其他的方式,做文本解析,提取出想要的正文。

为每个网页写特征分析这个还是太耗费开发的时间,我的思路是这样的。

Python的BeautifulSoup包大家都知道吧,

import BeautifulSoupsoup= BeautifulSoup.BeautifulSoup(html)

利用这个包先把html里script,style给清理了:

[script.extract() for script in soup.findAll('script')][style.extract() for style in soup.findAll('style')]

清理完成后,这个包有一个prettify()函数,把代码格式给搞的标准一些:

然后用正则表达式,把所有的HTML标签全部清理了:

reg1= re.compile("<[^>]*>")content= reg1.sub('',soup.prettify())

剩下的都是纯文本的文件了,通常是一行行的,把空白行给排除了,这样就会知道总计有多少行,每行的字符数有多少,我用excel搞了一些每行字符数的统计,如下图:

x坐标为行数,y坐标为该行的字符数

很明显,会有一个峰值,81~91行就应该是这个网页的正文部分。我只需要提取81~91行的文字就行了。

问题来了,照着这个思路,有什么好的算法能够通过数据分析的方式统计出长文本的峰值在哪几行?

BeautifulSoup不仅仅只是可以查找,定位和修改文档内容,同样也可以用一个好的格式进行输出显示。BeautifulSoup可以处理不同类型的输出:

BeautifulSoup中有内置的方法prettfy()来实现格式化输出。比如:

html_markup=“””<pclass=”ecopyramid”>

<liclass=”producerlist”>

<divclass=”name”>plants</div>

<divclass=”number”>100000</div>

<liclass=”producerlist”>

<divclass=”name”>algae</div>

<divclass=”number”>100000</div>

soup=BeautifulSoup(html_markup,“lxml”)

二、BeautifulSoup基本使用

1、 BeautifulSoup官方文档介绍:BeautifulSoup是一个可以从HTML或XML文件中提取数据的Python库。使用BeautifulSoup更多方便,避免使用正则表达式容易出错,提高效率。

2、 BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml。以下为BeautifulSoup官方文档对支持的解析器优缺点对比。

3、推荐使用lxml解释器,效率更高。注意:不同的解析器返回不同的结果

4、通过解析器,BeautifulSoup可以传入一段字符串或文件。

5、 Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种: Tag, NavigableString, BeautifulSoup, Comment。接下来使用以下文档进行说明。

6、可以看到a点只是返回第一个,如果需要历遍全部则需要用find_all('a')。

7、 tag有多种属性,其中两个最重要的就是name和attributes。name一般返回标签本身(soup返回document),注意,tag属性操作方法和字典一样。

8、上面说到节点选择可以直接利用标签,如<head>标签用soup.head,也可通过name和attrs可以直接获取属性,操作和字典一样。以上是直接获取的方式,当想要获取标签的子节点、父节点、兄弟节点则需要通过另外的方法。

9、.children是一个llist生成器,可以对子节点进行历遍循环

10、.descendants是返回所有子孙节点,比较children和descendants的输出区别

三、BeautifulSoup4中文文档

1、解析html并以友好形式显示:BeautifulSoup(html_doc,'html.parser') print(soup.prettify())

<html><head><title>The Dormouse's story</title></head>

<p class="title"><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>

from bs4 import BeautifulSoup

soup= BeautifulSoup(html_doc,'html.parser')

soup.title#获取标题<title>The Dormouse's story</title>

soup.title.string#获取标题标签内的内容 The Dormouse's story

soup.p['class']#获取第一个标签p的class内容

soup.find_all('a')#获取所有标签a,以列表返回

soup.find(id="link3")#根据属性查找

for link in soup.find_all('a'):

print(link.get('href'))

print(soup.get_text())#获取文档内容,不带任何标签

BeautifulSoup(markup,"html.parser")

BeautifulSoup(markup,"html5lib")

soup= BeautifulSoup('<b class="boldest">Extremely bold</b>')

tag.string.replace_with("No longer bold")

tag['class']='verybold'

6、tag.contents将子节点以列表输出。

通过tag的.children生成器,可以对tag的子节点进行循环:

for child in title_tag.children:

.descendants属性可以对所有tag的子孙节点进行递归循环

for child in head_tag.descendants:

7、循环输出不带标签的所有内容:

for string in soup.stripped_strings:

.next_sibling/.previous_sibling兄弟节点

.next_element和.previous_element指向解析过程中下一个被解析的对象

for tag in soup.find_all(re.compile("^b")):

soup.find_all(href=re.compile("elsie"), id='link1')

data_soup.find_all(attrs={"data-foo":"value"})

soup.find_all("a", class_="sister")

soup.find_all(string="Elsie")

soup.find_all("a", limit=2)#只返回2个

soup.html.find_all("title", recursive=False)#只检查1级子节点

find_parents()和 find_parent()

find_next_siblings()合 find_next_sibling()

find_previous_siblings()和 find_previous_sibling()

find_all_next()和 find_next()

find_all_previous()和 find_previous()

soup.select("p nth-of-type(3)")

soup.select("html head title")

soup.select("body> a")#>一级子标签,多级的不匹配

soup.select("#link1~.sister")

soup.select("#link1+.sister")

soup.select("[class~=sister]")

soup.select('a[href]')

soup.select('a[href=" http://example.com/elsie"]')

soup.select('a[href^=" http://example.com/"]')

soup.select('a[href$="tillie"]')

soup.select('a[href*=".com/el"]')

soup= BeautifulSoup("<a>Foo</a>")

markup='<a href="http://example.com/">I linked to<i>example.com</i></a>'

tag.insert(1,"but did not endorse")

soup= BeautifulSoup("<b>stop</b>")

soup.b.string.insert_before(tag)

soup.b.i.insert_after(soup.new_string(" ever"))

markup='<a href="http://example.com/">I linked to<i>example.com</i></a>'

markup='<a href="http://example.com/">I linked to<i>example.com</i></a>'

markup='<a href="http://example.com/">I linked to<i>example.com</i></a>'

markup='<a href="http://example.com/">I linked to<i>example.com</i></a>'

a_tag.i.replace_with(new_tag)

soup= BeautifulSoup("<p>I wish I was bold.</p>")

soup.p.string.wrap(soup.new_tag("b"))

soup.p.wrap(soup.new_tag("div"))

markup='<a href="http://example.com/">I linked to<i>example.com</i></a>'

prettify格式化输出,可以指定编码格式

get_text获得文档内容,指定分隔符

u'\nI linked to|example.com|\n'

如果不知道文档编码,使用UnicodeDamit来自动编码

from bs4 import UnicodeDammit

dammit= UnicodeDammit("Sacr\xc3\xa9 bleu!")

Beautiful Soup对文档的解析速度不会比它所依赖的解析器更快,如果对计算时间要求很高或者计算机的时间比程序员的时间更值钱,那么就应该直接使用 lxml.

换句话说,还有提高Beautiful Soup效率的办法,使用lxml作为解析器.Beautiful Soup用lxml做解析器比用html5lib或Python内置解析器速度快很多.

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

四、beautifulsoup库的作用

1、BeautifulSoup是python的一个库,其提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。BeautifulSoup4和lxml一样,BeautifulSoup也是一个HTML/XML的解析器,主要的功能也是如何解析和提取HTML/XML数据。

2、BeautifulSoup库是灵活又方便的网页解析库,处理高效,支持多种解析器。利用它不用编写正则表达式即可方便地实现网页信息的提取。prettify()方法可以将代码格式搞的标准一些,用soup.prettify()表示。在PyCharm中,用print(soup.prettify())来输出。

3、BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则Python会使用Python默认的解析器,lxml解析器更加强大,速度更快,推荐使用lxml解析器。

OK,关于beautifulsoup和beautifulsoup库怎么安装的内容到此结束了,希望对大家有所帮助。