python (3) 爬虫必备——requests库

爬虫必备——requests库

爬虫过程,其实我感觉就是快速多次地用程序模拟我们浏览网页的过程,而requests库就是一种较为简单的Python HTTP库。
因为爬虫过程要与http协议打交道,所以requests库的学习必不可少。
我们下面从函数入手,快速了解requests库

目录

爬虫必备——requests库
1 函数
2 requests.get()
3 常用操作
4 小节

函数

requests库函数
get 获取url位置的资源。
head 获取url位置的资源的头部信息。
post 请求向url位置的资源后附加新的数据。
put 请求向url位置存储一个资源,覆盖原来的资源。
patch 请求url位置的局部资源进行更新。
delete 请求删除url位置对应的全部资源。

requests.get()

所有函数中get函数应该是最基本的,通过get操作就能够得到服务器返回的所有相关资源。

import requests
url='https://www.baidu.com/'
r=requests.get(url)
print(r)

<Response [200]>

注:
1. get()函数返回的是一个Response对象,这个Response对象包含服务器返回的所有资源。
2. 在通过get()方法得到url后,requests库内部会自动生成一个Request对象 ,用于向服务器请求资源。

而完整的get函数除了url之外还包含着更多的参数:

requests.get(url,params=None,**kwargs)
url:页面的url链接。
params:url中的额外参数,字典或字节流格式。
**kwargs:13个访问控制的参数。

我们来说一下在爬虫过程中可能会用到的13个参数中的几个参数:

headers:头部访问信息,表明你的身份
timeout:设定超时时间,秒为单位
proxies:设定访问代理服务器,可用于隐藏原ip地址

在这里,有必要先介绍一下Response对象的一些属性与函数,以便于对于我们所得到的内容的分析。

Response对象属性
r.status_code HTTP返回状态。200表示成功,404表示失败。
r.text HTTP的相应内容的字符串形式。就是url对应的页面内容。
r.encoding 从HTTPheader中猜测的相应内容编码方式
r.apparent_encoding 从内容分析出的相应内容编码方式
r.content HTTP相应内容的二进制形式
Response对象函数
r.raise_for_status HTTP返回状态成功则返回None,返回状态失败则会出现Error。

常用操作

1.输出爬虫内容,要使用text属性

import requests
url='https://www.baidu.com/'
r=requests.get(url,headers=headers,timeout=5,proxies=proxies)
print(r.text)

输出结果

<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');
                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
  1. 有时我们要检验我们访问是否成功,这时候我们就可以用Response对象的raise_for_status()函数与try…except…来检测错误。
import requests

def get_url_text(url):
	try:
		r=requests.get(url,timeout=5)
	    r.raise_for_status()#是否访问网页正常
	    r.encoding=r.apparent_encoding#用网页内容的编码方式进行读码
		return r.text
	except:
		print('访问异常')

url='https://www.baidu.com/'
text=get_url_text(url)
print(text)

输出结果:

<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');
                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

2.有些网页是反爬虫的,我们在访问时就会出现403情况或者访问多次之后禁止你的IP禁止访问,对于这些情况,可以用多个ip以及多个headers进行突破:


# coding=utf-8
import urllib2 as ulb
import numpy as np
import PIL.ImageFile as ImageFile
import cv2
import random
import time
 
# 免费代理IP不能保证永久有效,如果不能用可以更新
# http://www.goubanjia.com/
proxy_list = [
    '183.95.80.102:8080',
    '123.160.31.71:8080',
    '115.231.128.79:8080',
    '166.111.77.32:80',
    '43.240.138.31:8080',
    '218.201.98.196:3128'
]
 
# 收集到的常用Header
my_headers = [
    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36",
    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14",
    "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)",
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
    'Opera/9.25 (Windows NT 5.1; U; en)',
    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
    'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
    'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
    'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
    "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7",
    "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 "
]
 
 
# 获取影像数据
def getImage(url):
    # 设置暂停时间为0.1秒
    t = 0.1
    time.sleep(t)
 
    # 随机从列表中选择IP、Header
    proxy = random.choice(proxy_list)
    header = random.choice(my_headers)
 
    print proxy, header
 
    # 基于选择的IP构建连接
    urlhandle = ulb.ProxyHandler({
    
    'http': proxy})
    opener = ulb.build_opener(urlhandle)
    ulb.install_opener(opener)
 
    # 用urllib2库链接网络图像
    response = ulb.Request(url)
 
    # 增加Header伪装成浏览器
    response.add_header('User-Agent', header)
 
    # 打开网络图像文件句柄
    fp = ulb.urlopen(response)
 
    # 定义图像IO
    p = ImageFile.Parser()
 
    # 开始图像读取
    while 1:
        s = fp.read(1024)
        if not s:
            break
        p.feed(s)
 
    # 得到图像
    im = p.close()
 
    # 将图像转换成numpy矩阵
    arr = np.array(im)
 
    # 将图像RGB通道变成BGR通道,用于OpenCV显示
    pic = np.zeros(arr.shape, np.uint8)
    pic[:, :, 0] = arr[:, :, 2]
    pic[:, :, 1] = arr[:, :, 1]
    pic[:, :, 2] = arr[:, :, 0]
 
    return pic
 
 
img = getImage('http://mt2.google.cn/vt/lyrs=s&hl=zh-CN&gl=CN&x=214345&y=107714&z=18')
cv2.imshow('image', img)
cv2.waitKey(0)

————————————————

这个代码来自链接:https://blog.csdn.net/u011808673/article/details/80609221

小节

学会requests库的一些皮毛,便能够从网页上获取信息;
学会正则表达式,就能够对获得的信息进行处理;

究竟什么是“正则表达式”?
https://blog.csdn.net/qq_45014265/article/details/104198195

学会文件与文件夹的操作,就能够将处理后的信息保存在自己的计算机中。

文件与文件夹的那些事
https://blog.csdn.net/qq_45014265/article/details/104180747

但是光说不练假把式,现在我们的屠龙大刀已经基本出鞘,可以去找一些小网站进行一下爬虫的尝试了!

猜你喜欢

转载自blog.csdn.net/qq_45014265/article/details/104215551