Python爬虫05-bs4

2022-07-31,,

bs4

  • 一、bs4使用
  • 二、bs4对象种类
  • 三、遍历子节点
    • 3.1 content
    • 3.2 children
    • 3.3 descendants
    • 3.4 string
    • 3.5 strings
    • 3.6 stripped strings
  • 四、遍历父节点
    • 4.1 parent
    • 4.2 parents
  • 五、遍历兄弟节点
    • 5.1 next_sibling
    • 5.2 previous_sibling
    • 5.3 next_siblings
    • 5.4 previous_siblings
  • 六、搜索树
    • 6.1 字符串过滤器
    • 6.2 正则表达式过滤器
    • 6.3 列表过滤器
    • 6.4 方法过滤器
    • 6.5 True过滤器
  • 七、find语句
    • 7.1 find()
    • 7.2 find_all()
    • 7.3 find_parents() ,find_parent() ,find_next_siblings() ,find_next_sibling()
    • 7.4 find_previous_siblings() ,find_previous_sibling ,find_all_next(), find_next()
  • 八、修改文档树

一、bs4使用

from bs4 import BeautifulSoup
import re
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<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>
"""

获取bs对象

soup = BeautifulSoup(html_doc,'lxml')
print(soup.prettify())   # 规范地打印文档内容
print(soup.title)  # 获取title标签内容 <title>The Dormouse's story</title>
print(soup.title.name) # 获取title标签名称 title
print(soup.title.string) # title标签里面的文本内容 The Dormouse's story
print(soup.p) # 获取p段落
print(soup.a)   # 通过标签导航的是第一个

r=soup.find_all('a')
print(r)  # 所有a标签内容,列表返回

for r1 in r:
    print(r1.get('href'))  # 所有a标签下href属性里的链接

s=soup.p
print(s['class'])   # ['title']

二、bs4对象种类

种类 意思
tag 标签
NavigableString 可导航的字符串
BeautifulSoup bs对象
Comment 注释
print(type(soup))  # <class 'bs4.BeautifulSoup'>
print(type(soup.title))  # <class 'bs4.element.Tag'>
print(type(soup.p.string)) # <class 'bs4.element.NavigableString'>

html_comment='<b><!--注释--></b>'
soup1 = BeautifulSoup(html_comment,'lxml')
print(type(soup1.b.string)) # <class 'bs4.element.Comment'>

三、遍历子节点

3.1 content

返回一个列表

html = '''
<div>
<a href='#'>张三</a>
<a href='#'>李四</a>
<a href='#'>王五</a>
</div>
'''
bs = BeautifulSoup(html,'lxml')
print(len(bs.contents))  # 1
print(bs.contents)
# [<html><body><div>
#<a href="#">张三</a>
#<a href="#">李四</a>
#<a href="#">王五</a>
#</div>
#</body></html>]
print(type(bs.contents))  # <class 'list'>

3.2 children

返回一个迭代器,可进行迭代

links = bs.div.children
print(type(links))  # <class 'list_iterator'>
for i in links:
    print(i)
# <a href="#">张三</a>
#
# <a href="#">李四</a>
#
# <a href="#">王五</a>

3.3 descendants

返回一个生成器遍历子子孙孙

print(len(soup.descendants))  
# TypeError: object of type 'generator' has no len()

for i in soup.descendants:
    print('-------------------')
    print(i)

3.4 string

获取标签里的内容

3.5 strings

返回一个生成器对象用来获取多个标签内容

strings=soup.strings
for i in strings:
    print(i)

3.6 stripped strings

和strings基本一致,但可去掉多余的空格

四、遍历父节点

4.1 parent

直接获得父节点

4.2 parents

获取所有父节点

五、遍历兄弟节点

5.1 next_sibling

下一个兄弟节点

html='<a><b>xxx</b><c>yyy</c></a>'
soup2=BeautifulSoup(html,'lxml')

b_tag=soup2.b
print(b_tag.next_sibling)  # <c>yyy</c>

5.2 previous_sibling

上一个兄弟节点

5.3 next_siblings

下一个所有兄弟节点

s=soup.find(id='link1')
for i in s.next_siblings:
    print(i)

5.4 previous_siblings

上一个所有兄弟节点

六、搜索树

6.1 字符串过滤器

print(soup.find('a'))   # 找一个直接返回结果
print(soup.find_all('a'))   # 找所有,返回列表

6.2 正则表达式过滤器

print(soup.find(re.compile('title')))
# <title>The Dormouse's story</title>

6.3 列表过滤器

print(soup.find_all(['p','a']))

6.4 方法过滤器

def fn(tag):
    return tag.has_attr('href')
s=soup.find_all(fn)
print(s)

6.5 True过滤器

print(soup.find_all(True))

七、find语句

7.1 find()

返回搜索到的第一条数据

7.2 find_all()

列表 形式返回所有搜索到的标签数据
参数 find_all(self, name=None, attrs={}, recursive=True, text=None,limit=None, **kwargs)
name:tag名称
attr:标签属性

print(soup.find_all('a'))

recursive : 是否递归搜索
默认recursive = True

print(soup.find_all('a',recursive=False))   # []

text : 文本内容

print(soup.find_all(text=re.compile('story')))
# ["The Dormouse's story", "The Dormouse's story"]

limlt : 限制返回条数

print(soup.find_all('a',limit=1))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]

kwargs : 关键字参数

print(soup.find_all(id='link1'))
print(soup.find_all(id = re.compile('link1'))) # 等同

7.3 find_parents() ,find_parent() ,find_next_siblings() ,find_next_sibling()

find_parents() 搜索所有父亲
find_parent() 搜索单个父亲
find_next_siblings()搜索所有兄弟
find_next_sibling()搜索单个兄弟

7.4 find_previous_siblings() ,find_previous_sibling ,find_all_next(), find_next()

find_previous_siblings() 往上搜索所有兄弟
find_previous_sibling() 往上搜索单个兄弟
find_all_next() 往下搜索所有元素
find_next()往下查找单个元素

八、修改文档树

修改标签名称

p_tag=soup.p
p_tag.name='w'

修改属性

p_tag['class']=['content']

修改string内容

p_tag.string = 'you need python'

append 向tag中添加内容

p_tag.append('hahaha')

decompose 删除段落

r = soup.find(class_ = 'title')
r.decompose()

本文地址:https://blog.csdn.net/weixin_47133012/article/details/107600777

《Python爬虫05-bs4.doc》

下载本文的Word格式文档,以方便收藏与打印。