Python模块之Requests Requests 模块

requests是在python中用于制造HTTP标准请求(request)头的模块,即模拟浏览器请求,它抽象了一个在美丽、简单的API背后发出请求的复杂性,即降低了HTTP请求头制造的复杂性
这样,以便您可以专注于与服务交互和在应用程序中使用数据

为何要使用requests模块
1、自动处理url编码
2、自动处理post请求参数
3、简化cookie代理的实现

request模块使用流程
1、指定url
2、使用requests模块发起请求
3、获取响应数据
4、进行持久化存储

requests模块安装:

pip install requests

requests模块导入:

import requests

常规的get请求

1、常规的get请求
需求:爬取搜狗首页的页面数据

import requests

# 指定url
url = "https://www.sogou.com/"

# 发起get请求:get方法会返回请求成功后的响应对象
response = requests.get(url=url)

# 获取响应中的数据值:.text可以获取响应对象中字符串形式的页面数据我、
page_data = response.text

print(page_data)

# 持久化操作
with open('./sogou.html','w',encoding='utf-8') as f:
    f.write(page_data)

response对象中其它重要的属性

# content:获取的是response对象中二进制(byte)类型的页面数据
print(response.content)

# status_code:返回一个响应状态码
print(response.status_code)

# headers:返回响应头信息
print(response.headers)

# url:获取请求的url
print(response.url)

2、携带参数的get请求
需求:指定一个词条,获取搜狗搜索结果所对应的页面数据
方式一:

import requests

# 指定url
url = "https://www.sogou.com/web?query=纽约&ie=utf-8"

response = requests.get(url=url)
page_text = response.text

with open('./niuyue.html','w',encoding='utf-8') as f:
    f.write(page_text)

方式二:

import requests

# 指定url
url = "https://www.sogou.com/web"

# 将参数封装到字典中
params = {
    'query':'纽约',
    'ie':'utf-8',
}
response = requests.get(url=url,params=params)

page_text = response.text

3、自定义请求头信息
自定义GET请求的一种常用方法是通过URL中的查询字符串参数传递值。需要用get()执行此操作,你可以将自定义数据传递给params方法

url地址格式如下图:

Python模块之Requests
Requests 模块

import requests

# 指定url
url = "https://www.sogou.com/web"

# 将参数封装到字典中
params = {
    'query':'纽约',
    'ie':'utf-8',
}

# 自定义请求头信息
headers={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
}
response = requests.get(url=url,params=params,headers=headers)

page_text = response.text
print(page_text)

基于ajax的get请求

基于ajax的get请求,实际调用的方法还是requests.get

需求:抓取豆瓣电影上电影详情的数据

import requests

url = "https://movie.douban.com/j/chart/top_list?"

# 封装ajax的get请求中携带的参数
params = {
    'type': '17',
    'interval_id': '100:90',
    'action':'',
    'start': '0',
    'limit': '200',
}

# 自定义请求头信息
headers={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
}

response = requests.get(url=url,params=params,headers=headers)

print(response.text)

常规的post请求

1、常规的post请求
需求:登录豆瓣网,获取登录成功后的页面数据

import requests

# 指定post请求的url
url = 'https://accounts.douban.com/j/mobile/login/basic'

# 封装post请求的参数
data={
    'ck': 'vMY5',
    'name': 'jasonminghao@163.com',
    'password': 'xmhdb1213',
    'remember': 'false',
    }

# 自定义请求头信息
headers={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
}

# 发起post请求
response = requests.post(url=url,data=data,headers=headers)

# 获取响应对象中的页面数据
page_text = response.text

print(page_text)

基于ajax的post请求

需求:爬取肯德基城市餐厅位置数据

import requests

url = "http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword"

# 处理post请求的参数
data = {
    'cname': '',
    'pid': '',
    'keyword': '广州',
    'pageIndex': '1',
    'pageSize': '10',
}

# 自定义请求头信息
headers={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
}

# 发起基于ajax的post请求
response = requests.post(url=url,data=data,headers=headers)

print(response.text)

综合项目实战

需求:爬取搜狗知乎某一个词条对应一定范围页码表示的页面数据

# 前三页面数据(1,2,3)
import requests
import os

# 创建一个文件夹
if not os.path.exists('./pages'):
    os.mkdir('./pages')


word = input('enter a word:')

# 动态指定页码的范围
start_pageNum = int(input('enter a start page number:'))
end_pageNum = int(input('enter a end page number:'))

# 指定url: 设计成一个具有通用的url
url = "https://www.sogou.com/sogou"

# 自定义请求头信息
headers={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
}

for page in range(start_pageNum,end_pageNum+1):
    param = {
        'query':word,
        'page':page,
        'id':'utf-8',
    }

    response = requests.get(url=url,params=param,headers=headers)

    # 获取响应中的页面数据(指定页码)
    page_text = response.text
    fileNmae = word+ "_" + str(page) + '.html'
    filePaath = './pages/' + fileNmae
    # 进行持久化存储
    with open(filePaath,'w',encoding='utf-8') as f:
        f.write(page_text)
        print('第%s页数据写入成功' %page)

requests模块高级

cookie基于用户的用户数据,当我们在某个网站里登录输入账号密码登录的时候,服务端会发送cookie给客户端,
cookie:服务器端使用cookie来记录客户端的状态信息

实现流程:
1、执行登录操作(获取cookie)
2、在发起个人主页请求时,需要将cookie携带到该请求中

注意:session对象:发送请求(会将cookie对象自动存储)

import  requests

session = requests.session()
#1、发起登录请求:将cookie获取,并存储到session


login_url = 'https://accounts.douban.com/j/mobile/login/basic'

# 封装post请求的参数
data={
    'ck': 'vMY5',
    'name': '',
    'password': '',
    'remember': 'false',
    }

# 自定义请求头信息
headers={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
}


# 使用session发起post请求
login_response = session.post(url=login_url,data=data,headers=headers)

cookie = login_response.cookies


# 2、对个人主页发起请求(session),获取响应页面数据

url = "https://www.douban.com/people/jason12313/"

response = session.get(url=url,headers=headers)
page_text = response.text

with open('./douban110.html','w',encoding='utf-8') as f:
    f.write(page_text)

requests代理

代理,称为第三方代理本体执行相关的事务,生活:代购,微商,房屋中介,

为何要使用代理?
很多时候我们去爬别人的网站时,如果爬的频率太高,例如一秒1000次请求,就会导致当前源IP地址被目标网站给禁止,那么我们就可以使用代理,让代理来作为源IP来执行爬虫。

代理分类
1、正向代理:代理客户端获取数据
2、反向代理:代理服务器端提供数据

免费代理提供商

  • www.goubanjia.com
  • 快代理
  • 西祠代理
import requests

url = 'http://www.baidu.com/s?ie=utf-8&wd=ip'
# 将代理IP封装到字典中
proxy = {
    'http':'183.146.213.198:80',
}

headers={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
}


# 更换网络IP
response = requests.get(url=url,proxies=proxy,headers=headers)
print(response.text)
with open('./daili.html','w',encoding='utf-8') as f:
    f.write(response.text)

验证码处理

  • 手动识别验证码
  • 云打码平台自动识别验证码

云打码平台处理验证码的实现流程:
1、对携带验证码的页面数据进行抓取
2、可以将页面数据中验证码进行解析,验证码图片下载到本地
3、可以将验证码图片提交给三方平台进行识别,返回验证码图片上的数据值