Python:网络爬虫

网络请求

实现HTTP网络请求的常见三种方式:urllib,urllib3,,requests。

1、urllib模块
该模块中提供了一个urlopen( )方法,可通过该方法指定URL发送网络请求来获取数据。

子模块名称描述
urllib.request该模块定义了打开URL(主要是HTTP)的方法和类,例如,身份验证等
urllib.error该模块主要包含异常类,基本的异常类是URLError
urllib.parse该模块定义的功能分为两大类:URL解析和URL引用
urllib.robotparser该模块用于解析robots.txt文件
#例:通过urllib.request模块的get方式实现发送请求并读取网页内容
import urllib.request	#导入模块
#打开指定需要爬取的网页
reponse=urllib.request.urlopen('http://www.baidu.com')
html=response.read()	#读取网页代码
print(html)				#打印读取内容
#例:通过urllib.request模块的post方式实现发送请求并读取网页内容
import urllib.parse
import urllib.request	#导入模块
#将数据使用urlencode编码处理后,再使用encoding设置为utf-8编码
data=bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf8')
#打开指定需要爬取的网页
response=urllib.request.urlopen('http://httpbin.org/post'.data=data)
html=response.read()	#读取网页代码
print(html)				#打印读取内容

2、urllib3模块
是一个功能强大,条理清晰的勇于HTTP客户端的Python库。(需要安装)

#例:通过Urllib3模块get请求实现发送网络请求
import urllib3
#创建PoolManager对象,用于处理与线程池的连接以及线程安全的所有细节
http=urllib3.PoolManager()
#对需要爬取的网页发送请求
response=http.request('GET','https://www.baidu.com/')
print(respinse.data)	#打印读取内容
#post请求
#对需要爬取的网页发送请求
response=http.request('POST','http://httpbin.org/post',fields-{'word':'hello'})

3、requests模块
在实现HTTP请求时要比urllib模块简化

#例:通过request模块get请求打印多种请求信息
import requests	#导入模块
response = requests.get('http://www,baidu.com')
print(response.status_code)	#打印状态码
print(response.url)	        #打印请求url
print(response.headers)		#打印头部信息
print(response.cookise)		#打印cookie信息
print(response.text)        #以文本形式打印网页源码
print(response.content)	    #以字节流形式打印网页源码
#通过request模块POST请求实现发送网络请求
import requests
data = {'word':'hello'} 	#表格参数
#对需要爬取的网页发送请求
request = requests.post('http://httpbin.org/post',data = data)
print(response.content)	    #以字节流形式打印网页源码
requests模块除了以上两种常用请求方式,还有以下多种网络请求方式:
requests.put('http://httpbin.org/put',data={'key':'value'})	#put请求
requests.delete('http://httpbin.org.delete')                #delete请求
requests.head('http://httpbin.org/get')	                    #head请求
requests.options('http://httpbin.org/get')	                #options请求

网络超时

#首先用代码来模拟一下网路超时的现象
import requests
#循环发送请求50次
for a in range(0,50):
 	try:	                        # 捕获异常
 		#设置超时为0.5秒
 		response = requests.get('https://www.baidu.com/',timeout=0.5)
 		print(response.status_code)	#打印状态码
 	except Exception as e:	        #捕获异常
 		print('异常‘+str(e)')	    #打印异常信息
#三种常见的网络异常类
import requests
from requests.exceptions import ReadTimeout,HTTPError,RequestException
for a in range(0,50):
    try:
        response = requests.get('http://www.baidu.com/',timeout=0.5)
        print(response.status_code)
    except ReadTimeout:	      #超时异常
        print('timeout')      
    except HTTPError:         #HTTP异常
        print('httperror')
    except RequestException:  #请求异常
        print('reqerror')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值