网络爬虫可以通过class属性的值,轻松地区分出<span class="green"></span>,<span class="red"></span>两种不同的标签。可以将网页的红色文字抓取而绿色的一个都不抓。例如网站:战争与和平
代码:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
html=urlopen("http://www.pythonscraping.com/pages/warandpeace.html")#抓取该网页
bsObj=BeautifulSoup(html)#用Beautifulsoup对该网页进行解析
nameList=bsObj.findAll("span",{"class":"green"}) #抓取绿色字,并且用nameList进行存储。
for name in nameList:
print(name.get_text())#打印绿色的字
get_text()去除HTML的所有标签,返回只剩文字的字符串,尽量在最后才使用.get_text(),以保证中间过程HTML标签的完整性。
结果:
Anna
Pavlovna Scherer
Empress Marya
Fedorovna
Prince Vasili Kuragin
Anna Pavlovna
St. Petersburg
the prince
Anna Pavlovna
Anna Pavlovna
the prince
the prince
the prince
Prince Vasili
Anna Pavlovna
Anna Pavlovna
the prince
Wintzingerode
King of Prussia
le Vicomte de Mortemart
Montmorencys
Rohans
Abbe Morio
the Emperor
the prince
Prince Vasili
Dowager Empress Marya Fedorovna
the baron
Anna Pavlovna
the Empress
the Empress
Anna Pavlovna's
Her Majesty
Baron
Funke
The prince
Anna
Pavlovna
the Empress
The prince
Anatole
the prince
The prince
Anna
Pavlovna
Anna Pavlovna
Beautifulsoup的find和findall函数
大部分情况下只使用前两个参数。
tag:标签参数,可以传入标签或者标签组成的列表,例如.fianAll({"h1","h2","h3","h4","h5","h6"})返回所有标题标签的列表。
attributes:一个python字典封装标签的若干个属性和对应的属性值。例如,
.findAll("span",{"class":"green"})
返回html绿色的span标签。
recursive:一个bool类型的变量,设置为true则查找标签参数的所有子标签,否则只查找文档的一级标签,默认为true。
text:用标签的文本内容进行匹配,而不是标签的属性,如果要找包含“the prince”内容的标签数量,可以这样
nameList = bsObj.findAll(text="the prince")
print(len(nameList))
limit:只适用于findAll方法,而find实质上等于findAll的limit=1的情况。
keyword:选择具有指定属性的标签,例如:
allText = bsObj.findAll(id="text")
print(allText[0].get_text())