Python BeautifulSoup的find和findAll

find(tag, attributes, recursive, text, keywords)参数列表:

tag:标签参数,可以传一个标签的名称或多个标签名称组成的 Python列表做标签参数。

attributes:属性参数

 recursive:递归参数,是一个布尔变量,在find函数内,这个默认是True,而且不能取修改为False,否则会出错,因为find只去查找第一级标签的内容,为True,默认递归查找所有,为False,则会出现矛盾,并报错。

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
content = re.compile(r'Prince')
html = urlopen("http://www.pythonscraping.com/pages/warandpeace.html")
bsObj = BeautifulSoup(html,"lxml")
nameList = bsObj.find("span",recursive = True,text = content)

text:文本参数,它是用标签的文本内容去匹配,而不是用标签的属性,可以同过正则表达式去匹配自己想要的内容

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
content = re.compile(r'Prince')
html = urlopen("http://www.pythonscraping.com/pages/warandpeace.html")
bsObj = BeautifulSoup(html,"lxml")
nameList = bsObj.find("span",text = content)
print(nameList.text)

keyword:关键字参数,可以让你选择那些具有指定属性的标签

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
content = re.compile(r'^W.+')
html = urlopen("http://www.pythonscraping.com/pages/warandpeace.html")
bsObj = BeautifulSoup(html,"lxml")
nameList = bsObj.find(class_='red')
print(nameList.get_text())

 和如下是一样的:

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
content = re.compile(r'^W.+')
html = urlopen("http://www.pythonscraping.com/pages/warandpeace.html")
bsObj = BeautifulSoup(html,"lxml")
nameList = bsObj.find("",{"class":"red"})
print(nameList.get_text())

可以理解为不管标签列表,根据属性参数来匹配。 

findAll(tag, attributes, recursive, text, limit, keywords)参数列表:

tag:标签参数,可以传一个标签的名称或多个标签名称组成的 Python列表做标签参数。

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
content = re.compile(r'h1|h2')
html = urlopen("http://www.pythonscraping.com/pages/warandpeace.html")
bsObj = BeautifulSoup(html,"lxml")
nameList = bsObj.findAll(content)

for n in nameList:
	print(n.text)

 

 

 

 attributes:属性参数,是用一个 Python 字典封装一个标签的若干属性和对应的属性值。

 recursive:递归参数,如果
recursive 设置为 True , findAll 就会根据你的要求去查找标签参数的所有子标签,以及子
标签的子标签。如果 recursive 设置为 False , findAll 就只查找文档的一级标签。 findAll
默认是支持递归查找的( recursive 默认值是 True );一般情况下这个参数不需要设置。

text:文本参数,它是用标签的文本内容去匹配,而不是用标签的属性,可以同过正则表达式去匹配自己想要的内容

 limit:范围限制参数,只用于 findAll 方法。 find 其实等价于 findAll 的 limit 等于1 时的情形。如果你只对网页中获取的前 x 项结果感兴趣,就可以设置它。但是要注意,这个参数设置之后,获得的前几项结果是按照网页上的顺序排序的,未必是你想要的那前几项。

keyword:关键字参数,可以让你选择那些具有指定属性的标签

正则表达式可以作为 BeautifulSoup 语句的任意一个参数,让你的目标元素查找工作极具灵活性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值