小编用心准备的一次纯干货分享,这篇文章主要介绍了Python 四种常见的基础爬虫方法,带你了解Python的四种基础爬虫方法,文章内容都是通过示例代码介绍的,对于小细节也描述的非常非常详细,对学习Python的朋友在学习上或者工作上都具有一定的参考学习价值,需要的朋友们现在就随着小编一起来学习学习吧!!!
一、Urllib方法
Urllib是python内置的HTTP请求库
import urllib.request
#1.定位抓取的url
url='http://www.baidu.com/'
#2.向目标url发送请求
response=urllib.request.urlopen(url)
#3.读取数据
data=response.read()
# print(data) #打印出来的数据有ASCII码
print(data.decode(‘utf-8’)) #decode将相应编码格式的数据转换成字符串
#post请求
import urllib.parse
url='http://www.iqianyue.com/mypost/'
#构建上传的data
postdata=urllib.parse.urlencode({
'name':'Jack',
'pass':'123456'
}).encode('utf-8') #字符串转化成字节流数据
html=urllib.request.urlopen(url,data=postdata).read()
print(html)
#headers针对检验头信息的反爬机制
import urllib.request
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
request1=urllib.request.Request('https://www.dianping.com/',headers=headers)#Request类构建了一个完整的请求
response1=urllib.request.urlopen(request1).read()
print(response1.decode('utf-8'))
#超时设置+异常处理
import urllib.request
import urllib.error
for i in range(20):
try:
response1=urllib.request.urlopen('http://www.ibeifeng.com/',timeout=0.01)
print('a')
except urllib.error.URLError as e:
print(e)
except BaseException as a: #所有异常的基类
print(a)
二、requests方法
–Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库
–urllib还是非常不方便的,而Requests它会比urllib更加方便,可以节约我们大量的工作。
–requests是python实现的最简单易用的HTTP库,建议爬虫使用requests库。
–默认安装好python之后,是没有安装requests模块的,需要单独通过pip安装
import requests
#get请求
r=requests.get('https://www.taobao.com/')
#打印字节流数据