从零开始写Python爬虫 --- 1.1 requests库的安装与使用

从零开始写Python爬虫 --- 1.1 requests库的安装与使用

从零开始写Python爬虫 --- 1.1 requests库的安装与使用


先来说说爬虫的原理:爬虫本质上是模拟人浏览信息的过程,只不过他通过计算机来达到快速抓取筛选信息的目的。所以我们想要写一个爬虫,最基本的就是要将我们需要抓取信息的网页原原本本的抓取下来。这个时候就要用到requests库了。


  • requests库的安装

requests库本质上就是模拟了我们用浏览器打开一个网页,发起请求是的动作。它能够迅速的把请求的html源文件保存到本地

他安装的方式非常简单:我们用pip工具在命令行里进行安装

$ pip install requests`

接着我们看一下是否成功安装了bs4库

$ pip list

看一下安装结果


  • requests库的基本使用:

#首先我们先导入requests这个包
import requests

#我们来吧百度的index页面的html源码抓取到本地,并用r变量保存
#注意这里,网页前面的 http://一定要写出来,它并不能像真正的浏览器一样帮我们补全http协议
r = requests.get("http://www.baidu.com")


#将下载到的内容打印一下:
print(r.text)

可以看到,百度的首页源码文件我们已经把他抓取到本地了。



上面的抓取过程中,我们用到了requests库的get方法,

这个方法是requests库中最常用的方法之一。

他接受一个参数(url)并返回一个HTTP response对象。

与get方法相同的,requests库还有许多其他常用方法


  • 下面我们来详细了解一下 requests.get 这个方法:


#这个方法可以接收三个参数,其中第二个默认为None 第三个可选
def get(url, params=None, **kwargs)
#作用是模拟发起GET请求
Sends a GET request.
#模拟获取页面的url链接
:param url: URL for the new :class:Request object. 
#额外参数 字典或字节流格式,可选
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:Request. 
# 十二个控制访问参数,比如可以自定义header
:param **kwargs: Optional arguments that request takes. 
# 返回一个Response对象
:return: :class:Response <Response> object 
:type: requests.Response

  • 我们来着重讲一下 **kwargs 这个参数


kwargs: 控制访问的参数,均为可选项

params : 字典或字节序列,作为参数增加到url中

data : 字典、字节序列或文件对象,作为Request的内容 json : JSON格式的数据,作为Request的内容

headers : 字典,HTTP定制头

cookies : 字典或CookieJar,Request中的cookie

auth : 元组,支持HTTP认证功能

files : 字典类型,传输文件

timeout : 设定超时时间,秒为单位

proxies : 字典类型,设定访问代理服务器,可以增加登录认证

allow_redirects : True/False,默认为True,重定向开关

stream : True/False,默认为True,获取内容立即下载开关

verify : True/False,默认为True,认证SSL证书开关

cert : 本地SSL证书路径

url: 拟更新页面的url链接

data: 字典、字节序列或文件,Request的内容

json: JSON格式的数据,Request的内容


常用的两个控制访问参数:


1. 假设我们需要在GET请求里自定义一个header头文件:


import requests

hd = {'User-agent':'123'}
r = requests.get('http://www.baidu.com', headers=hd)
print(r.request.headers)
'''
OUT:
{'User-agent': '123', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive
'}
'''


2. 假设我们要自定义一个代理池


pxs = { 'http': 'http://user:pass@10.10.10.1:1234',
        'https': 'https://10.10.10.1:4321' }
r = requests.get('http://www.baidu.com', proxies=pxs)

  • 详细了解Response对象


import requests
r = requests.get("http://www.baidu.com")

'''
Response(self)

The :class:Response <Response> object, which contains a server's response to an HTTP request.

'''
#HTTP请求的返回状态,比如,200表示成功,404表示失败
print (r.status_code)
#HTTP请求中的headers
print (r.headers)
#从header中猜测的响应的内容编码方式 
print (r.encoding)
#从内容中分析的编码方式(慢)
print (r.apparent_encoding)
#响应内容的二进制形式
print (r.content)

'''
status_code:200 

headers:
{'Server': 'bfe/1.0.8.18', 'Date': 'Tue, 02 May 2017 12:01:47 GMT', 'Content-Type': 'text/html', 'La
st-Modified': 'Mon, 23 Jan 2017 13:28:27 GMT', 'Transfer-Encoding': 'chunked', 'Connection': 'Keep-A
live', 'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Pragma': 'no
-cache', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Content-Encoding':
'gzip'}

encoding: ISO-8859-1

apparent_encoding:utf-8
'''


  • requests抓取网页的通用框架

import requests


def getHtmlText(url):
    try:
        r = requests.get(url, timeout=30)
        # 如果状态码不是200 则应发HTTOError异常
        r.raise_for_status()
        # 设置正确的编码方式
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return "Something Wrong!"


好了关于requests库我们今天就写到这,这是一个非常强大的库,

更多的功能大家可以去看一下官方的文档:快速上手 - Requests 2.10.0 文档



每天的学习记录都会 同步更新到:

微信公众号: findyourownway

知乎专栏:从零开始写Python爬虫 - 知乎专栏

blog : Ehco Blog

编辑于 2017-05-12 20:35