基于书籍《python网络数据采集》([美]Ryan Mitchell)
第二章2.2.1
用bs4在网站中读取所有颜色为绿色的字段。
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/warandpeace.html")
bsObj = BeautifulSoup(html,"html.parser")
nameList = bsObj.findAll("span",{"class":"green"})
for name in nameList:
print(name.get_text())
urlopen用来读取一个从网络获取的远程对象。
findAll函数一共有6个参数,这里用的前两个,第一个标签名,第二个为字典封装的一个标签的若干属性和对应的属性值,这里是“绿色”。
get_text()用来把html文档的所有标签都清除,返回一个只含文字的字符串。