爬虫-基于bs4库的HTML内容查找方法

bs4有一个find_all(name,attrs,recursive,string,**kwargs)方法,返回一个列表类型,存储查找的结果

name 对标签名称的检索字符串

attrs 对标签属性值的检索字符串,可标注属性检索,可查找某标签中是否含有特定的字符串

 recursive 是否对子孙全部检索,默认True

string <>...</>中字符串区域的检索字符串

举例说明:

name

soup.find_all('a')#返回a标签的内容
soup.find_all(['a','b'])#返回a和b标签的内容

for tag in soup.find_all(True):#打印文档中的所有标签名字
    print(tag.name)
'''
返回
html
head
title
body
p
b
p
a
a
'''
#使用正则化后:
import re#如果我们只想得到以b开头的标签,n那么我们需要正则表达式,re是相应的库
for tag in soup.find_all(re.compile('b')):
    print(tag.name)
#返回 body b

 attrs:

soup.find_all('p','course')#查找p标签中包含'course'的信息

soup.find_all(id='link1')
'''返回 [<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>]
'''
soup.find_all('link')#返回[]

import re
soup.find_all(id=re.compile('link'))#利用正则表达式查找包含link的标签内容
'''
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>,
 <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
'''

recursive:

soup.find_all('a',recursive=False)
#返回[]表明儿子节点上没有a标签

string:

soup.find_all(string='Basic Python')
#['Basic Python']

import re
soup.find_all(string=re.compile('python'))#所有在字符串中出现Python的字符串检索
'''
['This is a python demo page',
 'The demo python introduces several python courses.']
'''

另外,我们可以使用

<tag>(..)等价于<tag>.find_all(..)

soup(..)等价于soup.find_all(..)

find的扩展方法

方法 说明
<>.find() 搜索切只返回一个结果,字符串类型,同find_all()参数
<>.find_parents() 在先辈节点中搜索,返回列表类型,同find_all()参数
<>.find_parent() 在先辈节点中返回一个结果,同上
<>.find_next_siblings() 在后续平行节点中搜索,同上
<>.find_next_sibling() 在后续节点中返回一个结果,同上
<>.find_previous_siblings() 在前序平行节点中搜索,同上
<>.find_previous_sibling() 在前序平行节点中返回一个结果,同上
原文地址:https://www.cnblogs.com/rayshaw/p/8577120.html