![]()
Requests 的安装
1 2 3 4
| C:\Users\hp\AppData\Local\Programs\Python\Python35\Scripts`
pip install requests
|
![Requests 库的七个主要方法]()
get 方法
requests.get(url, params=None, **kwargs)
- url: 拟获取页面的 url 链接
- params: url 中的额外参数,字典或字节流格式,可选
- **kwargs: 12 个控制访问的参数
![Response 对象的属性]()
![]()
![理解 Requests 库的异常]()
![]()
response.raise_for_status() 在方法内部判断 r.status_code 是否等于 200,不需要
增加额外的if语句,该语句便于利用 try‐except 进行异常处理
![Requests 库的 7 个主要方法]()
![HTTP 协议对资源的操作]()
爬取网页的通用代码框架
1 2 3 4 5 6 7 8 9 10 11 12
| import requests
def getHTMLText(url): try: kv = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132'} response = requests.get(url, timeout = 10, headers = kv) response.raise_for_status() response.encoding = response.apparent_encoding return response.text except: return "产生 HTTPError"
|