为了账号安全,请及时绑定邮箱和手机立即绑定

Python爬虫基础之urllib与requests

标签:
Python

Python爬虫-Urllib方式

- 前言

此次我将讲述Python爬虫urllib与requests访问方式的一些基础的操作和遇到的一些坑,因为Python版本有2.7和目前的3.x版本,爬虫会有稍许区别,我会介绍一些区别,爬虫方式有多种,没有最好的方式,随着数据的需求加大,爬虫工具也会越来越简洁方便。但是如果你能了解多种爬虫方法,你也能对网络爬虫有更清楚的认识,初学者我建议使用requests方式,它会让你学起来更容易上手,urllib出现的较早,用起来稍微复杂点,但是如果你希望读懂很多爬虫大神写的东西,可能还需要了解一下。

一、Python2.7版本:
在2.7版本下,Python urllib模块分为两部分,urllib和urllib2。
(1)urllib和urllib2区别:

1、urllib提供urlencode方法,将需要传输的字典格式数据转换成网络传输的str格式如百度链接:https://www.baidu.com/s?wd=python2.7%20&rsv_spt=1   ‘&’符号后面就是我们传输的数据
2 、urllib2可以接受一个Request类对象,这样就意味着urllib2可以更改你的请求头数据以及更换ip代理,而urllib只能接受URL,无法更换请求数据
3、urllib还有一些方法如urlretrieve下载图片和视频,quote转码特殊字符是urllib2所没有的,所以我们经常需要使用urllib和urllib2协同工作

(2)请求网页基本命令:

这里加入了请求头参数user_agent,如果不带请求头很容易被反爬屏蔽。

import urllib2
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'  headers = { 'User-Agent' : user_agent }  
req = urllib2.Request('http://www.baidu.com',headers = headers)
res = urllib2.urlopen(req)print res.read()
(3)添加请求参数方式访问网页:

目前大多数网站都有使用post请求,post请求方式都需要自己提供请求参数,比如登录页面。get方式请求也有参数只是在url已经自己带上了参数如百度的搜索,所以并不需要额外的添加。

import urllib  
import urllib2  
url = 'http://www.server.com/login'user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'  values = {'username' : 'cqc',  'password' : 'XXXX' }  
headers = { 'User-Agent' : user_agent }  
data = urllib.urlencode(values)  
request = urllib2.Request(url, data, headers)  
response = urllib2.urlopen(request)  
page = response.read()
(4)添加代理访问网页:

添加代理是反反爬策略中最实用的方法,如果有大量代理会让你的爬虫更快速高效的获取大量数据。

    url=''
    headers['User-Agent']='Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36'
    req=urllib2.Request(url,headers=headers)
    ip = '113.122.42.161:6675'
    proxy_handler = urllib2.ProxyHandler({'http':ip})
    opener = urllib2.build_opener(proxy_handler)
    urllib2.install_opener(opener)
    response = urllib2.urlopen(req)
    data=response.read().decode('utf-8')
(5)配置cookie

有的网站访问需要验证cookie信息,cookie也可以用来免登陆操作。

import urllib2import cookielib   #python2.7 需要用这个req = urllib2.request(url,headers=headers)
cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
urllib2.install_opener(opener)
response = urllib2.urlopen(req)
二、Python 3.5版本:
(1)py2.7与py3.5版本urllib的区别:

Python3.5 版本下将python2.7版本的urllib和urllib2 合并在一起成一个新的urllib,方法并入error、parse、request、response下,连接请求基本在request中通过urllib.request调用,数据处理的一些方式放入parse中,如2.7版本的urlencode方法就放在parse下,通过urllib.parse.urlencode调用,所以区别不大,重点介绍几个需要注意的。

(2)请求方式:
 import  urllib
 headers = {}
 url=''
 ip = '113.122.42.161:6675'
 headers['User-Agent']='Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36'
 #urllib2中的Request和urlopen都合并到urllib.request下
 req=urllib.request.Request(url,headers=headers)
 proxy_handler = urllib.request.ProxyHandler({'http': ip})
 opener = urllib.request.build_opener(proxy_handler)
 urllib.request.install_opener(opener) 
 #使用自己安装好的Opener 
 response=urllib.request.urlopen(req,timeout=10) #timeout 设置最长请求时间,如果超时,停止请求
(3)配置cookie:
import urllibimport http.cookiejar  #和2.7不同req = urllib.request.Request(action_url,data=data,headers=header) #data是传送参数,post请求常用cookie = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie))
urllib.request.install_opener(opener)
response = urllib.request.urlopen(req,timeout=60)

Python爬虫-Requests方式

  • 介绍
    Requests是Python中的HTTP客户端库,网络请求更加直观方便,它与Urllib最大的区别就是在爬取数据的时候连接方式的不同。urllb爬取完数据是直接断开连接的,而requests爬取数据之后可以继续复用socket,并没有断开连接。个人比较推荐使用requests方式,常见的组合是Requests+BeautifulSoup(解析网络文本的工具库),解析工具常见的还有正则,xpath,个人觉得xpath和BeautifulSoup标签类解析学一种就好了,正则都可以学,用的地方很多,这个看个人喜好。

(1)请求网页基本命令:
import requests
url = ''headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' } 
response  = requests.get(url,headers = headers) 
print(response.text)
(2)Post方式请求(添加请求参数):
import requests
url = ''headers = {}
data = {'key':'value'}
response = requests.post(url,data=data,headers=headers)#get方式添加请求参数方法#response = requests.get(url,params=data,headers=headers)print(response.status_code)
print(response.text)

如果用post请求登录用session对象比较好,它会帮助你保存前次操作,比如做验证码的时候,你识别完了,然后输入正确验证信息,但是用requests,将再一次刷新验证码。

(3)使用session对象访问
import requests
url = ''headers = {}
data = {'key':'value'}
s= requests.Session()
response = s.post(url,data=data,headers=headers)
print(response.status_code)
print(response.text)
(4)添加代理请求
import requests
proxies={"http":"http://....","https":"http://...."}
response = resquests.get("",proxies=proxies)
(5)返回请求信息的有关命令
import requests
resoonse= requestss.get()
response.text   #网页内容response.content   #图片 视频二进制内容response.json    ##返回json格式网页内容response.cookies  #返回cookiesresponse.status_code  #返回状态码response.headers  #返回头信息response.url   #返回请求的urlresponse,apparent_encoding    #返回网页编码格式response.history       #返回历史记录

结语

综上讲了urllib和requests的基本操作,希望能给一些对爬虫感兴趣的童鞋一个具体的概念,方法只是一种工具,试着去爬一爬会更容易上手,网络也会有很多的坑,做爬虫更需要大量的经验来应付复杂的网络情况。如果发现文章有错误的地方,欢迎指出,一起探讨学习。后续,我会写一些具体的爬虫项目。



作者:黑羊的皇冠
链接:https://www.jianshu.com/p/1efa672156d3


点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消