爬取网页的通用代码框架
2021-05-23 本文已影响0人
闲云野鹤_23dd
1、什么是网页的通用代码框架?
就是一组代码;能够准确的可靠地爬取网页上的内容。
2、网络的异常处理:

注意:6、7的区别

r.raise_for_status()使用方法:


代码如下:
import requests
def getHTMLText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status()#如果状态不是200,引发HTTPError异常
r.encoding=r.apparent_encoding#根据响应内容指定编码格式utf-8
return r.text
except:
return '产生异常'
if name == 'main':
url='https://www.baidu.com'
print(getHTMLText(url))
Http协议和Requests库的 方法:
http协议内容请参考:HTTP入门详解 - 简书 (jianshu.com)
是不是很熟悉,和request库的七个主要七个方法很像。


head()方法更节省带宽:



put()与post()类似。