首先来看看这两个方法之间的区别
findAll(tag,attributes,recursive,
text,limit,keywords)
find(tag,attributes,recursive,text,
keywords)
其实大部分时间很多人用这两个方法都只需要前两个参数,但它们之间的区别就在于参数limit
那么我们来看一看参数limit
到底有什么用?
首先来看一个例子:
爬取p.html
文件
#test.py文件
from urllib.request import urlopen
from bs4 import BeautifulSoup
html=urlopen('file:///C:/Users/Ly/Desktop/pyhton/p.html')
bs=BeautifulSoup(html,'html.parser')
list_1=bs.findAll('h1',class_='ji')
print(list_1)
<!-- p.html文件-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>I DO NOT KNOW</title>
<style type="text/css">
h1{
font-family: 'Courier New', Courier, monospace;
size: 18px;
color: aqua;
}
</style>
</head>
<body>
<h1 class="ji">HAHA</h1>
<h1 class="ji">WUWU</h1>
<h1 class="ji">KKK</h1>
</body>
</html>
运行结果是
[<h1 class="ji">HAHA</h1>, <h1 class="ji">WUWU</h1>, <h1 class="ji">KKK</h1>]
findAll
方法默认提取只包含在<h1 class="ji"></h1>
的内容并将结果保存在列表里。
如果将limit=1
添加在上面代码中,那么就是告诉findAll
只获取符合条件的前1项结果,所以结果就是:
[<h1 class="ji">HAHA</h1>]
而find
方法则和limit=1
时的findAll
函数相差不大,在test.py
中用find
替换findAll
,运行结果如下:
<h1 class="ji">HAHA</h1>
注意,一个结果返回的是列表,另一个则是字符串,所以在用findAll
方法的基础上再用到.get_text()
清除最后结果的标签时,一定要用遍历列表的方式清除列表中每一个元素的标签,而不是整个列表,不然会出现以下错误:
AttributeError: ResultSet object has no attribute 'get_text'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?
第一次写文章,希望大家支持,有什么错误还望大家指出