ライブラリのチュートリアルをリクエスト
HTTPライブラリを使用する方が簡単urllibはして比較しました。
リクエスト
リクエストをGET:だけする必要がrequests.get()
GETリクエストを達成し、応答を得ることができ、着信対応するURLを処理します。POSTリクエストを使用してrequests.post()
次のようにメソッドのコードは次のとおりです。
#GET请求
import requests
response = requests.get('https://www.baidu.com/')
print(response)
#POST请求
import requests
data = {'name': 'germey', 'age': '22'}
response = requests.post("http://httpbin.org/post", data=data)
print(response.text)
ライブラリー法、直接実装されたURLにパラメータを追加することができParamsパラメータに渡されたパラメータの形式で辞書より便利に、引数に渡された要求を提供します。次のようにデータフォームPOSTリクエストは、直接そのような固有のコードを配置してもよいです。
# GET请求
import requests
data = {
'name': 'germey',
'age': 22
}
response = requests.get("http://httpbin.org/get", params=data)
print(response.text)
# POST请求
import requests
data = {'name': 'germey', 'age': '22'}
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
}
response = requests.post("http://httpbin.org/post", data=data, headers=headers)
print(response.json())
セットヘッダ:ヘッダは、着信情報指示get()
次のように関数のパラメータに対応する、POSTのリクエストヘッダは、同じ方法が提供さ(対応するコードブロック上記参照)コードです。
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
}
response = requests.get("https://www.zhihu.com/explore", headers=headers)
print(response.text)
応答
JSONの構文解析:リクエスト・ライブラリは、レスポンスはJSON形式を返す場合、JSONを解析するためのシンプルで簡単な方法を提供
.json()
する方法を使用しているリクエストのJSON形式に直接保存することができjson.loads()
、全く同じ効果が機能し。コードは以下の通りであります:import requests import json response = requests.get("http://httpbin.org/get") print(type(response.text)) print(response.json())#使用json方法解析 print(json.loads(response.text))#使用loads方法转化为json,与上一行比较返回结果一样。 print(type(response.json()))
バイナリデータを取得します:なWebページから写真やビデオなどのデータを使用する必要が取得
.content
する方法をして、コンテンツをローカルに保存するための保存操作ファイルを使用します。コードは以下の通りであります:import requests response = requests.get("https://github.com/favicon.ico")#通过传入URL下载图片 print(type(response.text), type(response.content)) print(response.text) print(response.content)#文件的二进制编码,与urllib库一样。 with open('favicon.ico', 'wb') as f:#保存文件 f.write(response.content) f.close()
ステータスコード:使用して
.status_code()
サーバから返さ方法入手可能なステータス・コード、状態コードの各々は、以下の表に対応する状態に対応します。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'),
サーバのステータスは、ステータスコードによって取得することができます。
import requests
response = requests.get('http://www.jianshu.com/hello.html')
print(type(response.status_code), response.status_code)
exit() if not response.status_code == requests.codes.not_found else print('404 Not Found')#方法一:使用状态码对应的信息进行验证。
response = requests.get('http://www.jianshu.com')
print(type(response.status_code), response.status_code)
exit() if not response.status_code == 200 else print('Request Successfully')
#使用状态码值进行验证
#其实我不理解这两种方法的语法结构
#我看了一下官方文档,如果发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),我们可以通过 Response.raise_for_status() 来抛出异常:
import requests
bad_r = requests.get('http://www.jianshu.com')
print(bad_r.status_code)
bad_r.raise_for_status()
高度な操作
- ファイルをアップロード
import requests
#用open方法打开图片,储存到file中,保存到字典files中。
files = {'file': open('favicon.ico', 'rb')}
#发送Request时将其传入对应的参数中
response = requests.post("http://httpbin.org/post", files=files)
print(response.text)#获取并打印结果
- クッキー:提供するライブラリを要求
.cookies
JSON形式としてクッキーを取得するには、クッキーを取得する方法を。
import requests
response = requests.get('http://www.jianshu.com')
print(type(response.cookies), response.cookies)
print(response.cookies)#可以直接导出cookie不需要先声明CookieJar类,更简单。
for key, value in response.cookies.items():#打印json格式的cookies
print(key + '=' + value)
クッキーは、シミュレートされた着陸によって達成することができ、シミュレーションの対話が同じコールである必要があります一度、ことに注意することは、いくつかの呼び出しは、要求が実装は、同じ会話中に複数の要求を開始し、セッションクラスで提供されている場合。
import requests
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')#设置cookies
#一次请求并获取反馈
r = requests.get(url, cookies=cookies)
print(r.text)
#多次请求
s = requests.Session()
s.get(url, cookies=cookies)
response = s.get(url)
print(response.text)
- 証明書の検証:HTTPSサイトを登るとき、ブラウザは最初の証明書の合法性をテストします、証明書を直接SSLErrorスロー問題がある場合、プログラムは終了します。次のような事態を避けるために、あなたは、コードの除去を使用することができ、証明書は警告が発行されます検証しない、検証しないことを選択することができ、コードは次のとおりです。
import requests
#消除警告操作
from requests.packages import urllib3
urllib3.disable_warnings()
#verify参数设置为False,不验证
response = requests.get('https://www.12306.cn', verify=False)
print(response.status_code)
- プロキシ設定:次のように、エージェント情報は、辞書に格納され、対応するパラメータを渡すことができます。
import requests
#http代理
proxies = {
"http": "http://user:[email protected]:9743/",
"https": "https://127.0.0.1:9743",
}#如果代理有密码,可以在域名前进行设置,用冒号分割。
proxies = {
'http': 'socks5://127.0.0.1:9742',
'https': 'socks5://127.0.0.1:9742'
}#如果使用SSR代理,需要提前安装'requests[socks]',如上设置即可
response = requests.get("https://www.taobao.com", proxies=proxies)
print(response.status_code)
- タイムアウト処理:指定した時間にアクセスするためには、異常なタイムアウトを捕捉するために、クラスのタイムアウトに属する見つける必要があります。
import requests
from requests.exceptions import ReadTimeout
try:
response = requests.get("http://httpbin.org/get", timeout = 0.5)
print(response.status_code)
except ReadTimeout:#Timeout属于ReadTimeout异常类
print('Timeout')
- 認証設定:いくつかのサイトへのアクセス、認証があるだろうだろうに検証されていないページを開くことができません。で、ユーザー名とパスワード認証で着信タプル型。
import requests
r = requests.get('http://120.27.34.24:9001', auth=('user', '123'))
print(r.status_code)
- 例外処理:例:
import requests
from requests.exceptions import ReadTimeout, ConnectionError, RequestException
try:
response = requests.get("http://httpbin.org/get", timeout = 0.5)
print(response.status_code)
except ReadTimeout:
print('Timeout')
except ConnectionError:
print('Connection error')
except RequestException:
print('Error')
- その他の機能
print(type(response.url), response.url)
print(type(response.history), response.history)
print(response.text)#与urllib库中的response.read()功能相同