一.BeautifulSoup解析器
二.BeautifulSoup类的基本元素
三.html遍历方法
1.标签树的下行遍历
.contents返回的类型是列表
.children和.descendants返回迭代类型,只能用在for循环中
2.标签树的上行遍历
3.标签树的平行遍历
四.信息标记的三种方法
xml:标签对的形式,常用于internet上的信息交互
json:有类型的键值对,需要双引号,移动应用和云端节点的信息通信,无注释
haml:无类型的键值对,不需要双引号,各类系统的配置文件,有注释易读
五.基于bs4库的html内容查找方法
简写形式:
tds=tr('td') #简写,相当于tr.find_all(‘td'),存为列表
url='...'
r=requests.get(url,timeout=30)
html=r.text
a=soup.find_all('a')
for tr in soup.find('tbody').children:
...
六.大学排名爬虫实例
'''
1.获得网页内容
2.提取信息
3.输出
'''
import requests
from bs4 import BeautifulSoup
import bs4
#获取网页内容
def getHTMLText(url):
try:
r=requests.get(url,timeout=30) #超时30s
r.raise_for_status()#产生异常
r.encoding=r.apparent_encoding
return r.text
except:
return '爬取失败'
#提取需要的信息
def fillUnivList(ulist,html): #html是r.text
soup=BeautifulSoup(html,'html.parser') #做成一锅汤,用html解析
for tr in soup.find('tbody').children:
if isinstance(tr,bs4.element.Tag):#isinstance判断类型,如果不是bs4库定义的tag类型将过滤掉
tds=tr('td') #简写,相当于tr.find_all(‘td'),存为列表
ulist.append([tds[0].string,tds[1].string,tds[3].string])
#按一定格式输出
def printUnivList(ulist,num):#注意中文输出对齐问题
tplt='{0:^10}\t{1:{3}^10}\t{2:^10}'#{3}指如果要填充就用format的第三个变量进行填充,也就是中文空格
print(tplt.format('排名','学校名称','总分',chr(12288)))#chr(12288)表示中文空格
for i in range(num):
u=ulist[i]
print(tplt.format(u[0],u[1],u[2],chr(12288)))
def main():
uinfo=[] #大学信息的列表
url='http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html'
html=getHTMLText(url)
fillUnivList(uinfo,html)
printUnivList(uinfo,20) #输出前20
main()