實驗環境 Python3+jupyter
1、程序框架
2、工具層 utils.py
1. 單例函數jquery
def singleton(cls): instance = cls() instance.__call__ = lambda: instance return instance
3、網絡層 jquery.py
要求:
1. 實現get、post請求
2. 添加cookie和headers
3. 處理http狀態碼異常
4. 判斷返回數據是json 仍是str
5. 每一個用戶的cookies獨立
6. 實現cookie文件和cookie的轉化web
代碼:json
import json,requests import http.cookiejar as cookielib from utils import singleton class session(requests.Session): def __init__(self,headers={},cookie_file=None): requests.Session.__init__(self) self.cookies = cookielib.LWPCookieJar(filename=cookie_file) try:self.cookies.load(ignore_discard=True) except:print("failed load cookie_file") self.headers=headers self.auth = ('user', 'pass') self._type='str' def save(self): self.cookies.save() @singleton class http(): def get(self,s,url,data=None): r=s.get(url,params=data) self.error(r.status_code) return self.res_data(r,s._type) def post(self,s,url,data): r=s.post(url,data=data) self.error(r.status_code) return self.res_data(r,s._type) def error(self,code): if code==200:return elif code==403:raise RuntimeError('403 - Forbidden') elif code==404:raise RuntimeError('404 - Not Found') def res_data(self,r,_type): if _type=='json':return json.loads(r.content) return r.content
4、代碼測試api
headers={ 'Host': 'api.live.bilibili.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0', 'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2', 'Accept-Encoding': 'gzip, deflate, br', 'Referer': 'https://live.bilibili.com/', 'Origin': 'https://live.bilibili.com', 'Connection': 'keep-alive' } s=session(headers,'cookie.txt') s._type='json' url='https://api.live.bilibili.com/room/v1/Room/playUrl' data={ 'cid':7603080, 'quality':0, 'platform': 'web' } r=http.get(s,url,data) for d in r['data']['durl']:print(d['url'])
failedload cookie_file [https://qn.live-play.acgvideo.com/live-qn/165966/live_267605959_3403844.flv?wsSecret=06028657c2cc08ff816df9d9d505a5a3&wsTime=1538217562](https://qn.live-play.acgvideo.com/live-qn/165966/live_267605959_3403844.flv?wsSecret=06028657c2cc08ff816df9d9d505a5a3&wsTime=1538217562) [https://qn.live-play.acgvideo.com/live-qn/165966/live_267605959_3403844.flv?wsSecret=06028657c2cc08ff816df9d9d505a5a3&wsTime=1538217562](https://qn.live-play.acgvideo.com/live-qn/165966/live_267605959_3403844.flv?wsSecret=06028657c2cc08ff816df9d9d505a5a3&wsTime=1538217562) [https://qn.live-play.acgvideo.com/live-qn/165966/live_267605959_3403844.flv?wsSecret=06028657c2cc08ff816df9d9d505a5a3&wsTime=1538217562](https://qn.live-play.acgvideo.com/live-qn/165966/live_267605959_3403844.flv?wsSecret=06028657c2cc08ff816df9d9d505a5a3&wsTime=1538217562) [https://qn.live-play.acgvideo.com/live-qn/165966/live_267605959_3403844.flv?wsSecret=06028657c2cc08ff816df9d9d505a5a3&wsTime=1538217562](https://qn.live-play.acgvideo.com/live-qn/165966/live_267605959_3403844.flv?wsSecret=06028657c2cc08ff816df9d9d505a5a3&wsTime=1538217562)