一、requests库的使用入门
requests.request() 构造一个请求,支撑以下各方法
requests.get() 获取HTML网页的主要方法,对应于HTTP的GRT
requests.head() 获取HTML网页头信息
requests.post() 对应于HTTP的POST
requests.put() 对应于HTTP的PUT
requests.patch() 向HTML提交局部修改请求
requests.delete() 向HTML提交删除请求
二、ROBOTS协议
爬虫可能被网站拒绝 需要修改Header
爬虫时注意\robots.txt
三、BeautifulSoup
属性: Tag、Name、Attributes、NavigableString、Comment
遍历:
平行遍历: .contents .children .descendants
上行遍历: .parent .parents
下行遍历: .next_sibling .next_siblings .previous_sibling .previous_siblings
个别函数:
HTML文本格式化: .prettify()
查找函数: .find_all()
四、实例-----大学排名
import requests
from bs4 import BeautifulSoup
import bs4
def getHTMLText(url):
try:
r = requests.get(url, timeout = 30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
print("failed")
return ""
def fillUnivList(ulist, html):
soup = BeautifulSoup(html, "html.parser")
for tr in soup.find('tbody').children:
if isinstance(tr, bs4.element.Tag):
tds = tr('td')
ulist.append([tds[0].string, tds[1].string, tds[2].string])
def printUnivList(ulist, num):
print("{:^10}\t{:^6}\t{:^10}".format("排名", "学校名称", "得分"))
for i in range(num):
u = ulist[i]
print("{:^10}\t{:^6}\t{:^10}".format(u[0], u[1], u[2]))
def main():
uinfo = []
url = "http://www.zuihaodaxue.com/zuihaodaxuepaiming2016.html"
html = getHTMLText(url)
fillUnivList(uinfo,html)
printUnivList(uinfo,20) #20