Python爬虫(三)— 深入了解Requests模块
in python爬虫 with 0 comment

Python爬虫(三)— 深入了解Requests模块

in python爬虫 with 0 comment

前言

以下关于Requests的内容讲解,强烈推荐深入了解的查看官方文档。

中文版:Requests、 http://cn.python-requests.org/zh_CN/latest/

Requests

Get请求

以下代码使用了对 get请求的参数、请求的header、请求的超时设置、请求的返回参数进行示例。可自行根据需要进行删减。

import requests

# 第一种设置请求参数的方法:get请求的参数写成字典的形式,作为get请求的params参数传入
data = {
    "name":"luozheng",
    "age":22
}
# 第二种设置请求参数的方法  response = requests.get("http://httpbin.org/get?name=luozhengfan&age=23")

# 添加header
headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"
}
response = requests.get("http://httpbin.org/get", params=data, headers=headers, timeout=5)
print(type(response))
print(response.status_code)
print(type(response.text))
print(response.text)
print(response.cookies)
# 二进制,用于解析视频、图片等
print(response.content)
print(response.content.decode("utf-8"))
print(response.history)
"""
<class 'requests.models.Response'>
200
<class 'str'>
{
  "args": {
    "age": "22", 
    "name": "luozheng"
  }, 
  ......
}
<RequestsCookieJar[]>
b'{\n  "args": {\n    "age": "22", \n    "name": "luozheng"\n  }, ......}'
{
  "args": {
    "age": "22", 
    "name": "luozheng"
  }, 
  ......
}
[]
"""

Post请求

Post请求的与上面的Get请求类似,唯一不同的是对data参数进行设置时,只能使用字典对参数进行设置,并将参数作为data赋值传入。

import requests

# 设置post请求的参数
data = {
    "name":"luozheng",
    "age":22
}
# 添加header
headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"
}
response = requests.post("http://httpbin.org/post", data=data, headers=headers, timeout=5)
print(response.text)
# 二进制,用于解析视频、图片等
print(response.content)
print(response.content.decode("utf-8"))

其他用法

import requests
import json

response = requests.get("http://httpbin.org/get?name=luozhengfan&age=23")
print(type(response.text))
print(response.json())
print(json.loads(response.text))
print(type(response.json()))
"""
<class 'str'>
{'args': {'age': '23', 'name': 'luozhengfan'}, ...}
{'args': {'age': '23', 'name': 'luozhengfan'}, ...}
<class 'dict'>
"""
import requests

response= requests.get("http://www.baidu.com")
if response.status_code == requests.codes.ok:
    print("访问成功")
"""
100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),

Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect',
'resume_incomplete', 'resume',), # These 2 to be removed in 3.0

Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),

Server Error.
500: ('internal_server_error', 'server_error', '/o\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication'),
"""

Requests高级用法

主要包括了文件上传,证书验证,代理设置,认证设置。

import requests

files = {"files":open("wechat.png","rb")}
response = requests.post("http://httpbin.org/post", files=files)
print(response.text)
"""
{
  "args": {}, 
  "data": "", 
  "files": {
    "files": "data:application/octet-stream;base64,iVBORw0KGg......YII="
  }, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "38735", 
    "Content-Type": "multipart/form-data; boundary=a18f2223063180433033132aee71a297", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.22.0"
  }, 
  "json": null, 
  "origin": "117.183.8.254, 117.183.8.254", 
  "url": "https://httpbin.org/post"
}
"""
import requests

# 消除警告InsecureRequestWarning
requests.packages.urllib3.disable_warnings()
response = requests.get("https://www.12306.cn",verify=False)
print(response.status_code)
import requests

proxies= {
    "http":"http://127.0.0.1:9999",
    "https":"http://127.0.0.1:8888"
}
response  = requests.get("https://www.baidu.com",proxies=proxies)
print(response.text)
"""
如果代理需要设置账户名和密码,只需要将字典更改为如下:
proxies = {
"http":"http://user:password@127.0.0.1:9999"
}

如果你的代理是通过sokces这种方式则需要pip install "requests[socks]"
proxies= {
"http":"socks5://127.0.0.1:9999",
"https":"sockes5://127.0.0.1:8888"
}
"""
import requests

from requests.auth import HTTPBasicAuth

response = requests.get("http://120.27.34.24:9001/",auth=HTTPBasicAuth("user","123"))
print(response.status_code)
"""
import requests

response = requests.get("http://120.27.34.24:9001/",auth=("user","123"))
print(response.status_code)
"""

requests cookie与会话维持session cookie

## 获取cookie

import requests

response = requests.get("http://www.baidu.com")
print(response.cookies)

for key, value in response.cookies.items():
    print(key+"="+value)
"""
<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
BDORZ=27315
"""

##设置cookie

import requests

jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/cookies')

url = 'http://httpbin.org/cookies'
r = requests.get(url, cookies=jar)
print(r.text)
"""
{
  "cookies": {
    "gross_cookie": "blech", 
    "tasty_cookie": "yum"
  }
}
"""

以下介绍三种设置会话session的cookie的方法,第一种简单,第二种可以设置cookie的作用域,第三种每个请求都要设置。

import requests
s = requests.Session()
s.get("http://httpbin.org/cookies/set/number/123456")
response = s.get("http://httpbin.org/cookies")
print(response.text)
import requests

s = requests.session()
mycookie = {"tasty_cookie":"yum","gross_cookie":"blech"}

s.cookies = requests.utils.add_dict_to_cookiejar(s.cookies, mycookie)

r = s.get("http://httpbin.org/cookies")
print(r.text)
"""
{
  "cookies": {
    "gross_cookie": "blech", 
    "tasty_cookie": "yum"
  }
}
"""
import requests

s = requests.session()

s.cookies.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
s.cookies.set('gross_cookie', 'blech', domain='httpbin.org', path='/cookies')

r = s.get("http://httpbin.org/cookies")
print(r.text)
import requests

s = requests.session()

mycookie = {"tasty_cookie":"yum","gross_cookie":"blech"}

r = s.get("http://127.0.0.1:80",cookies = mycookie)
print(r.text)
Responses