加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

爬虫利器BeautifulSoup模块使用

发布时间:2020-12-17 00:52:28 所属栏目:Python 来源:网络整理
导读:table style="height: 30px; background-color: #afeeee; width: 1266px; ; width: 1266px;" border="0" tr td span style="font-size: 16px;"一、简介 /td /tr /table BeautifulSoup?是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换
<tr>
<td><span style="font-size: 16px;">一、简介</td>
</tr></table>

BeautifulSoup?是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式,同时应用场景也是非常丰富,你可以使用它进行XSS过滤,也可以是使用它来提取html中的关键信息。

官方文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/

<table style="height: 30px; background-color: #afeeee; width: 1266px; ; width: 1266px;" border="0">

1.安装模块

2.安装解析器(可以使用内置的解析器)

$ apt-get install Python-

3.各个解释器优缺点比较

创建对象

将一段文档传入BeautifulSoup 的构造方法,就能得到一个文档的对象,可以传入一段字符串或一个文件句柄。

bs4 soup = BeautifulSoup(open(<span style="color: #800000;">"<span style="color: #800000;">index.html<span style="color: #800000;">"<span style="color: #000000;">))

soup = BeautifulSoup(<span style="color: #800000;">"<span style="color: #800000;">...<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #008000;">#<span style="color: #008000;">##使用解释器###
soup = BeautifulSoup(open(<span style="color: #800000;">"<span style="color: #800000;">index.html<span style="color: #800000;">"),features=<span style="color: #800000;">"<span style="color: #800000;">lxml<span style="color: #800000;">")

基本使用

使用html示例

bs4 = test

wd

soup=BeautifulSoup(html_doc,features=<span style="color: #800000;">"<span style="color: #800000;">html.parser<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">print(soup.head)<span style="color: #008000;">#<span style="color: #008000;">获取head标签
<span style="color: #0000ff;">print(soup.head.title)<span style="color: #008000;">#<span style="color: #008000;">获取title
<span style="color: #0000ff;">print(soup.body.a)

?tips:通过soup.方式获取的标签如果标签有多个,只返回第一个标签

1.name:标签名称,如:标签的名称为a,标签名称为span

操作方式:获取、设置,设置以后会使得原文档标签改变

<span style="color: #0000ff;">from bs4 <span style="color: #0000ff;">import<span style="color: #000000;"> BeautifulSoup
html_doc = <span style="color: #800000;">"""<span style="color: #800000;">

test

wd

=BeautifulSoup(html_doc,features=(soup.body.name) soup.body.p.name= (soup)

2.attrs:标签属性(如id,class,style等)操作方式:获取、设置

bs4 = test

wd

=BeautifulSoup(html_doc,features=(soup.body.p.attrs) soup.body.p.attrs[]= (soup.body.p.attrs.get()) soup.body.p.attrs[]=[,] (soup)

3.string:标签内容(类似js中的innertext),该属性只能适用于标签中只有一个内容,若有多个子标签都有内容则返回None

操作方式:获取、设置

bs4 = test

wd

=BeautifulSoup(html_doc,features=(soup.head.title.string) soup.head.title.string= (soup)

?4.contents:将子节点以列表方式输出,返回list(),列表中仅仅含有子标签

bs4 = test

=BeautifulSoup(html_doc,features==(type(a))

5.childen:和contents不同,它返回列表生成器,使用循环获取,生成器中只含有子标签

bs4 = test

=BeautifulSoup(html_doc,features== item (item)

?6.descendants:返回子子孙孙标签,返回迭代器

bs4 = test

=BeautifulSoup(html_doc,features== k,v (k,v)

?7.strings&stripped_strings:返回所有子子孙孙标签内容生成器,stripped_strings和strings区别是,stripped_strings输出的是去掉空格的内容。

bs4 = test

wd

soup=BeautifulSoup(html_doc,features=<span style="color: #800000;">"<span style="color: #800000;">html.parser<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">for k,v <span style="color: #0000ff;">in<span style="color: #000000;"> enumerate(soup.body.strings):
<span style="color: #0000ff;">print<span style="color: #000000;">(k,v)
<span style="color: #0000ff;">for k1,v1 <span style="color: #0000ff;">in<span style="color: #000000;"> enumerate(soup.body.stripped_strings):
<span style="color: #0000ff;">print<span style="color: #000000;">(k1,v1)
复制代码

8.parent&parents:父标签(节点)和祖辈节点,父标签一般只有一个,祖辈节点可能很多,parents返回生成器。

bs4 = test

soup=BeautifulSoup(html_doc,features=<span style="color: #800000;">"<span style="color: #800000;">html.parser<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">print(soup.a.parent)<span style="color: #008000;">#<span style="color: #008000;">a标签的父节点
b=<span style="color: #000000;">list(enumerate(soup.a.parents))
<span style="color: #0000ff;">print<span style="color: #000000;">(b)
<span style="color: #0000ff;">for k,v <span style="color: #0000ff;">in enumerate(soup.a.parents): <span style="color: #008000;">#<span style="color: #008000;">a标签的祖辈节点
<span style="color: #0000ff;">print(k,v)

9.next_sibling&previous_sibling:兄弟标签(节点),一般只有一个,没有返回none

bs4 = test

soup=BeautifulSoup(html_doc,features=<span style="color: #800000;">"<span style="color: #800000;">html.parser<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">print<span style="color: #000000;">(soup.p.next_sibling)
<span style="color: #0000ff;">print<span style="color: #000000;">(soup.p.previous_sibling)
<span style="color: #0000ff;">for k,v <span style="color: #0000ff;">in<span style="color: #000000;"> enumerate(soup.p.next_siblings):
<span style="color: #0000ff;">print(k,v)

10.next_siblings&previous_siblings:返回所有兄弟标签的生成器。

bs4 = test

soup=BeautifulSoup(html_doc,v <span style="color: #0000ff;">in<span style="color: #000000;"> enumerate(soup.p.next_siblings):
<span style="color: #0000ff;">print<span style="color: #000000;">(k,v1 <span style="color: #0000ff;">in<span style="color: #000000;"> enumerate(soup.p.previous_siblings):
<span style="color: #0000ff;">print(k1,v1)

11.hidden:隐藏或显示当前标签,只会把当前标签隐藏,子孙标签不变

soup=BeautifulSoup(html_doc,features== soup.find(=True (soup)

12.is_empty_element,是否是空标签(是否可以是空)或者自闭合标签

<table style="height: 30px; background-color: #afeeee; width: 1266px; ; width: 1266px;" border="0">

<tr>
<td><span style="font-size: 16px;">四、强大的过滤器</td>
</tr></table>

这里所说的过滤器可以理解为查找文档的参数,可以是字符串,可以是name,可以是正则表达式等等,过滤器依赖于过滤方法,下面介绍常用过滤方法。

1.find_all(self,name=None,attrs={},recursive=True,text=None,limit=None,**kwargs): 获取匹配的所有标签(节点),返回列表

  • name:标签名,字符串对象会被忽略,可以是字符串、正则、列表、方法或者True
  • attrs:标签属性,字典形式,用于查找标签的特殊属性
  • recursive:是否递归查找,设置Flase,只查找子节点.
  • text:文档中的字符串内容,与name参数一样,可接受字符串、正则、列表、或者True
  • limit:限制列表中个数,如limit=3只返回前三个
bs4 = The Dormouse's story asdf
The Dormouse's story总共

f

ie, and ; and they lived at the bottom of a well.
ad
sf

=BeautifulSoup(html_doc,features=

<span style="color: #008000;">#<span style="color: #008000;"> tags = soup.find_all('a',limit=1)<span style="color: #008000;">

<span style="color: #008000;"> print(tags)

<span style="color: #008000;">#<span style="color: #008000;"> tags = soup.find_all(name='a',attrs={'class': 'sister'},text='Lacie')<span style="color: #008000;">

<span style="color: #008000;"> # tags = soup.find(name='a',class_='sister',text='Lacie')<span style="color: #008000;">

<span style="color: #008000;"> print(tags)

<span style="color: #008000;">#<span style="color: #008000;"> ####### 列表 #######<span style="color: #008000;">

<span style="color: #008000;"> v = soup.find_all(name=['a','div'])<span style="color: #008000;">

<span style="color: #008000;"> print(v)

<span style="color: #008000;">#<span style="color: #008000;"> v = soup.findall(class=['sister0','sister'])<span style="color: #008000;">

<span style="color: #008000;"> print(v)

<span style="color: #008000;">#<span style="color: #008000;"> v = soup.find_all(text=['Tillie'])<span style="color: #008000;">

<span style="color: #008000;"> print(v,type(v[0]))

<span style="color: #008000;">#<span style="color: #008000;"> v = soup.find_all(id=['link1','link2'])<span style="color: #008000;">

<span style="color: #008000;"> print(v)

<span style="color: #008000;">#<span style="color: #008000;"> v = soup.find_all(href=['link1','link2'])<span style="color: #008000;">

<span style="color: #008000;"> print(v)

<span style="color: #008000;">#<span style="color: #008000;"> ####### 正则 #######
<span style="color: #0000ff;">import<span style="color: #000000;"> re
<span style="color: #008000;">#<span style="color: #008000;"> rep = re.compile('p')<span style="color: #008000;">

<span style="color: #008000;"> rep = re.compile('^p')<span style="color: #008000;">

<span style="color: #008000;"> v = soup.find_all(name=rep)<span style="color: #008000;">

<span style="color: #008000;"> print(v)

<span style="color: #008000;">#<span style="color: #008000;"> rep = re.compile('sister.*')<span style="color: #008000;">

<span style="color: #008000;"> v = soup.findall(class=rep)<span style="color: #008000;">

<span style="color: #008000;"> print(v)

<span style="color: #008000;">#<span style="color: #008000;"> rep = re.compile('http://www.oldboy.com/static/.*')<span style="color: #008000;">

<span style="color: #008000;"> v = soup.find_all(href=rep)<span style="color: #008000;">

<span style="color: #008000;"> print(v)

<span style="color: #008000;">#<span style="color: #008000;"> ####### 方法筛选 #######<span style="color: #008000;">

<span style="color: #008000;"> def func(tag):<span style="color: #008000;">

<span style="color: #008000;"> return tag.has_attr('class') and tag.has_attr('id')<span style="color: #008000;">

<span style="color: #008000;"> v = soup.find_all(name=func)<span style="color: #008000;">

<span style="color: #008000;"> print(v)

<span style="color: #008000;">#<span style="color: #008000;"> ## get,获取标签属性<span style="color: #008000;">

<span style="color: #008000;"> tag = soup.find('a')<span style="color: #008000;">

<span style="color: #008000;"> v = tag.get('id')<span style="color: #008000;">

<span style="color: #008000;"> print(v)

2.find_all(self,**kwargs): 获取匹配的一个(节点),返回tag对象,用法与find_all相同

bs4 = The Dormouse's story asdf
The Dormouse's story总共

f

ie,features== soup.find((tag.name)

3.其他过滤方法:

tag.find_next(...) tag.find_all_next(...) tag.find_next_sibling(...) tag.find_next_siblings(...) tag.find_all_previous(...) tag.find_previous_sibling(...) tag.find_previous_siblings(...) tag.find_parents(...)

<span style="color: #008000;">#<span style="color: #008000;"> 参数同find_all

<table style="height: 30px; background-color: #afeeee; width: 1266px; ; width: 1266px;" border="0">

<tr>
<td><span style="font-size: 16px;">五、CSS选择器</td>
</tr></table>

BeautifulSoup不仅提供了筛选器,也提供了选择器,用法和前端css一样,其中.代表class,#代表id

html_doc = The Dormouse's story asdf
The Dormouse's story总共

f

ie, and ; and they lived at the bottom of a well.
ad
sf

soup = BeautifulSoup(html_doc,features=<span style="color: #800000;">"<span style="color: #800000;">lxml<span style="color: #800000;">"<span style="color: #000000;">)
soup.select(<span style="color: #800000;">"<span style="color: #800000;">title<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">p nth-of-type(3)<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">body a<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">html head title<span style="color: #800000;">"<span style="color: #000000;">)

tag = soup.select(<span style="color: #800000;">"<span style="color: #800000;">span,a<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">head > title<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">p > a<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">p > a:nth-of-type(2)<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">p > #link1<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">body > a<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">#link1 ~ .sister<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">#link1 + .sister<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">.sister<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">[class~=sister]<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">#link1<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">"<span style="color: #800000;">a#link2<span style="color: #800000;">"<span style="color: #000000;">)

soup.select(<span style="color: #800000;">'<span style="color: #800000;">a[href]<span style="color: #800000;">'<span style="color: #000000;">)

soup.select(<span style="color: #800000;">'<span style="color: #800000;">a[href="http://example.com/elsie"]<span style="color: #800000;">'<span style="color: #000000;">)

soup.select(<span style="color: #800000;">'<span style="color: #800000;">a[href^="http://example.com/"]<span style="color: #800000;">'<span style="color: #000000;">)

soup.select(<span style="color: #800000;">'<span style="color: #800000;">a[href$="tillie"]<span style="color: #800000;">'<span style="color: #000000;">)

soup.select(<span style="color: #800000;">'<span style="color: #800000;">a[href*=".com/el"]<span style="color: #800000;">'<span style="color: #000000;">)

<span style="color: #0000ff;">from bs4.element <span style="color: #0000ff;">import<span style="color: #000000;"> Tag

<span style="color: #0000ff;">def<span style="color: #000000;"> default_candidate_generator(tag):
<span style="color: #0000ff;">for child <span style="color: #0000ff;">in<span style="color: #000000;"> tag.descendants:
<span style="color: #0000ff;">if <span style="color: #0000ff;">not<span style="color: #000000;"> isinstance(child,Tag):
<span style="color: #0000ff;">continue
<span style="color: #0000ff;">if <span style="color: #0000ff;">not child.has_attr(<span style="color: #800000;">'<span style="color: #800000;">href<span style="color: #800000;">'<span style="color: #000000;">):
<span style="color: #0000ff;">continue
<span style="color: #0000ff;">yield<span style="color: #000000;"> child

tags = soup.find(<span style="color: #800000;">'<span style="color: #800000;">body<span style="color: #800000;">').select(<span style="color: #800000;">"<span style="color: #800000;">a<span style="color: #800000;">",_candidate_generator=<span style="color: #000000;">default_candidate_generator)
<span style="color: #0000ff;">print<span style="color: #000000;">(type(tags),tags)

<span style="color: #0000ff;">from bs4.element <span style="color: #0000ff;">import<span style="color: #000000;"> Tag
<span style="color: #0000ff;">def<span style="color: #000000;"> default_candidate_generator(tag):
<span style="color: #0000ff;">for child <span style="color: #0000ff;">in<span style="color: #000000;"> tag.descendants:
<span style="color: #0000ff;">if <span style="color: #0000ff;">not<span style="color: #000000;"> isinstance(child,_candidate_generator=default_candidate_generator,limit=1<span style="color: #000000;">)
<span style="color: #0000ff;">print(type(tags),tags)

<table style="height: 30px; background-color: #afeeee; width: 1266px; ; width: 1266px;" border="0">

<tr>
<td><span style="font-size: 16px;">六、tag对象常用方法</td>
</tr></table>

1.clear():将标签的所有子标签全部清空(保留标签名)

2.decompose():递归的删除所有的标签

soup=BeautifulSoup(html_doc,features== soup.find( (soup)

3.extract():递归的删除所有的标签,并获取删除的标签

soup=BeautifulSoup(html_doc,features== soup.find(=(soup)

4.decode()&decode_contents():decode,转换为字符串(含当前标签),decode_contents(不含当前标签)

soup=BeautifulSoup(html_doc,features== soup.find(==(type(b))

5.encode()&encode_contents():encode,转换为bytes类型(含当前标签),encode_contents(不含当前标签)

soup=BeautifulSoup(html_doc,features== soup.find(==(type(b))

6.?has_attr():检查标签是否具有该属性,返回布尔类型

soup=BeautifulSoup(html_doc,features== soup.find((tag.has_attr())

7.?get_text():获取标签内部文本内容

soup=BeautifulSoup(html_doc,features== soup.find((tag.get_text())

8.index():检查标签在某标签中的索引位置

<span style="color: #008000;">#<span style="color: #008000;"> tag = soup.find('body')<span style="color: #008000;">

<span style="color: #008000;"> for i,v in enumerate(tag):<span style="color: #008000;">

<span style="color: #008000;"> print(i,v)

9.append():在当前标签内部追加一个标签

10.insert():在当前标签内部指定位置插入一个标签

11.insert_after()&insert_before(): 在当前标签后面或前面插入

12.replace_with(): 在当前标签替换为指定标签

13.setup():设置标签之间关系

14.wrap():将指定标签把当前标签包裹起来

<span style="color: #008000;">#<span style="color: #008000;"> tag = soup.find('a')<span style="color: #008000;">

<span style="color: #008000;"> v = tag.wrap(soup.find('p'))<span style="color: #008000;">

<span style="color: #008000;"> print(soup)

15.?unwrap():去掉当前标签,将保留其包裹的标签

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读