python 3.requestモジュール詳細解教程


requestsはApache 2 licensedライセンスを使ったHTTPライブラリです。pythonで編纂して、urllib 2モジュールよりもっと簡潔です。RequestはHTTP接続保持と接続池をサポートし、cookieを使ってセッションを保持し、ファイルアップロードをサポートし、自動応答内容の符号化をサポートし、国際化URLとPOSTデータ自動符号化をサポートします。python内蔵モジュールをベースに高度なパッケージ化を行い、pythonがネットワーク要求を行う際には、人間的になり、Requestsを使用することで、ブラウザにあるあらゆる操作を簡単に行うことができます。現代、国際化、友好。requestsは自動的に持続的な接続keep-aliveを実現します。
基礎入門
モジュールをインポート
import requests
要求の送信の簡潔
例コード:ウェブページを取得します。
import requests
r = requests.get('https://github.com/Ranxf')       #          get  
r1 = requests.get(url='http://dict.baidu.com/s', params={
     'wd': 'python'})      #     get  
私たちはこの方法を使って、次のような方法を使うことができます。
requests.get(‘https://github.com/timeline.json’)                                # GET  
requests.post(“http://httpbin.org/post”)                                        # POST  
requests.put(“http://httpbin.org/put”)                                          # PUT  
requests.delete(“http://httpbin.org/delete”)                                    # DELETE  
requests.head(“http://httpbin.org/get”)                                         # HEAD  
requests.options(“http://httpbin.org/get” )                                     # OPTIONS  
urlのためのパラメータ
>>> url_params = {
     'key':'value'}       #      ,    None        url 
>>> r = requests.get('your url',params = url_params)
>>> print(r.url)
  your url?key=value
応答の内容
r.encoding                       #       
r.encoding = 'utf-8'             #    
r.text                           # encoding      。         ,                  。
r.content                        #     (   )  。        ,        gzip   deflate   。
r.headers                        #             ,          ,         ,        None
r.status_code                     #     
r.raw                             #       ,    urllib   response   ,   r.raw.read()   
r.ok                              #   r.ok               
 #*    *#
r.json()                         #Requests    JSON   , json    ,          json   ,          
r.raise_for_status()             #    ( 200  )    
postはjsonリクエストを送信します。
import requests
import json
r = requests.post('https://api.github.com/some/endpoint', data=json.dumps({
     'some': 'data'}))
print(r.json())
カスタムヘッドとクッキー情報
header = {
     'user-agent': 'my-app/0.0.1''}
cookie = {
     'key':'value'}
 r = requests.get/post('your url',headers=header,cookies=cookie) 
data = {
     'some': 'data'}
headers = {
     'content-type': 'application/json',
           'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}
r = requests.post('https://api.github.com/some/endpoint', data=data, headers=headers)
print(r.text)
応答状態コード
requests方法を使用すると、サーバ応答の内容が格納されたレスポンスオブジェクトが返されます。上記の例で述べたr.text、r.status_code…テキスト方式の応答体の例を取得します。r.textにアクセスすると、その応答のテキスト符号化を使って復号します。そして、その符号化を修正して、r.textにユーザー定義の符号化を使って復号します。
1 r = requests.get('http://www.itwhy.org')
2 print(r.text, '
{}
'
.format('*'*79), r.encoding) 3 r.encoding = 'GBK' 4 print(r.text, '
{}
'
.format('*'*79), r.encoding)
サンプルコード:
1 import requests
2 
3 r = requests.get('https://github.com/Ranxf')       #          get  
4 print(r.status_code)                               #       
5 r1 = requests.get(url='http://dict.baidu.com/s', params={
     'wd': 'python'})      #     get  
6 print(r1.url)
7 print(r1.text)        #           
実行結果:
/usr/bin/python 3.5/home/rxf/python 3_1000/1000/python 3_server/python 3_requests/demo 1.py 200http://dict.baidu.com/s?wd=python ……Process finished with exit code 0
r.status_code                      #    200,     r.raise_for_status()     
応答
r.headers                                  #      ,   
r.requests.headers                         #            
r.cookies                                  #  cookie
r.history                                  #       ,          allow_redirects = false      
タイムアウト
r = requests.get('url',timeout=1)           #      ,       
セッションオブジェクトは、要求にまたがっていくつかのパラメータを保持することができます。
s = requests.Session()
s.auth = ('auth','passwd')
s.headers = {
     'key':'value'}
r = s.get('url')
r1 = s.get('url1') 
エージェント
proxies = {
     'http':'ip1','https':'ip2' }
requests.get('url',proxies=proxies)
まとめ:
# HTTP    
# get  
r = requests.get('https://github.com/timeline.json')
# post  
r = requests.post("http://m.ctrip.com/post")
# put  
r = requests.put("http://m.ctrip.com/put")
# delete  
r = requests.delete("http://m.ctrip.com/delete")
# head  
r = requests.head("http://m.ctrip.com/head")
# options  
r = requests.options("http://m.ctrip.com/get")

#       
print(r.content) #         ,       
print(r.text) #         

#URL    
payload = {
     'keyword': '  ', 'salecityid': '2'}
r = requests.get("http://m.ctrip.com/webapp/tourvisa/visa_list", params=payload) 
print(r.url) #   http://m.ctrip.com/webapp/tourvisa/visa_list?salecityid=2&keyword=  

#  /      
r = requests.get('https://github.com/timeline.json')
print (r.encoding)


#json  
r = requests.get('https://github.com/timeline.json')
print(r.json()#    import json    

#      
url = 'http://m.ctrip.com'
headers = {
     'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'}
r = requests.post(url, headers=headers)
print (r.request.headers)

#  post  
url = 'http://m.ctrip.com'
payload = {
     'some': 'data'}
r = requests.post(url, data=json.dumps(payload)) #     payload string   dict,     dumps       

# post       
url = 'http://m.ctrip.com'
files = {
     'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)

#      
r = requests.get('http://m.ctrip.com')
print(r.status_code)
    
#    
r = requests.get('http://m.ctrip.com')
print (r.headers)
print (r.headers['Content-Type'])
print (r.headers.get('content-type')) #              
    
# Cookies
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies['example_cookie_name']    #  cookies
    
url = 'http://m.ctrip.com/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies) #  cookies

#      
r = requests.get('http://m.ctrip.com', timeout=0.001)

#      
proxies = {
     
           "http": "http://10.10.1.10:3128",
           "https": "http://10.10.1.100:4444",
          }
r = requests.get('http://m.ctrip.com', proxies=proxies)


#            ,     :
proxies = {
     
    "http": "http://user:[email protected]:3128/",
}
インスタンスコード
GET要求
# 1、     
   
 import requests
   
 ret = requests.get('https://github.com/timeline.json')
   
 print(ret.url)
 print(ret.text)
   
   
   
 # 2、     
   
 import requests
   
 payload = {
     'key1': 'value1', 'key2': 'value2'}
 ret = requests.get("http://httpbin.org/get", params=payload)
   
 print(ret.url)
 print(ret.tex
POSTリクエスト
# 1、  POST  
  
import requests
  
payload = {
     'key1': 'value1', 'key2': 'value2'}
ret = requests.post("http://httpbin.org/post", data=payload)
  
print(ret.text)
  
  
# 2、          
  
import requests
import json
  
url = 'https://api.github.com/some/endpoint'
payload = {
     'some': 'data'}
headers = {
     'content-type': 'application/json'}
  
ret = requests.post(url, data=json.dumps(payload), headers=headers)
  
print(ret.text)
print(ret.cookies)
要求パラメータ
def request(method, url, **kwargs):
    """Constructs and sends a :class:`Request `.

    :param method: method for the new :class:`Request` object.
    :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`.
    :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
    :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
        to add for the file.
    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
    :param timeout: (optional) How long to wait for the server to send data
        before giving up, as a float, or a :ref:`(connect timeout, read
        timeout) ` tuple.
    :type timeout: float or tuple
    :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
    :type allow_redirects: bool
    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
    :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``.
    :param stream: (optional) if ``False``, the response content will be immediately downloaded.
    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
    :return: :class:`Response ` object
    :rtype: requests.Response

    Usage::

      >>> import requests
      >>> req = requests.request('GET', 'http://httpbin.org/get')
      
    """
def param_method_url():
    # requests.request(method='get', url='http://127.0.0.1:8000/test/')
    # requests.request(method='post', url='http://127.0.0.1:8000/test/')
    pass


def param_param():
    # -      
    # -       
    # -      (ascii    )

    # requests.request(method='get',
    # url='http://127.0.0.1:8000/test/',
    # params={'k1': 'v1', 'k2': '   '})

    # requests.request(method='get',
    # url='http://127.0.0.1:8000/test/',
    # params="k1=v1&k2=   &k3=v3&k3=vv3")

    # requests.request(method='get',
    # url='http://127.0.0.1:8000/test/',
    # params=bytes("k1=v1&k2=k2&k3=v3&k3=vv3", encoding='utf8'))

    #   
    # requests.request(method='get',
    # url='http://127.0.0.1:8000/test/',
    # params=bytes("k1=v1&k2=   &k3=v3&k3=vv3", encoding='utf8'))
    pass


def param_data():
    #      
    #       
    #      
    #        

    # requests.request(method='POST',
    # url='http://127.0.0.1:8000/test/',
    # data={'k1': 'v1', 'k2': '   '})

    # requests.request(method='POST',
    # url='http://127.0.0.1:8000/test/',
    # data="k1=v1; k2=v2; k3=v3; k3=v4"
    # )

    # requests.request(method='POST',
    # url='http://127.0.0.1:8000/test/',
    # data="k1=v1;k2=v2;k3=v3;k3=v4",
    # headers={'Content-Type': 'application/x-www-form-urlencoded'}
    # )

    # requests.request(method='POST',
    # url='http://127.0.0.1:8000/test/',
    # data=open('data_file.py', mode='r', encoding='utf-8'), #      :k1=v1;k2=v2;k3=v3;k3=v4
    # headers={'Content-Type': 'application/x-www-form-urlencoded'}
    # )
    pass


def param_json():
    #  json                 ,json.dumps(...)
    #           body ,  Content-Type  {'Content-Type': 'application/json'}
    requests.request(method='POST',
                     url='http://127.0.0.1:8000/test/',
                     json={
     'k1': 'v1', 'k2': '   '})


def param_headers():
    #           
    requests.request(method='POST',
                     url='http://127.0.0.1:8000/test/',
                     json={
     'k1': 'v1', 'k2': '   '},
                     headers={
     'Content-Type': 'application/x-www-form-urlencoded'}
                     )


def param_cookies():
    #   Cookie     
    requests.request(method='POST',
                     url='http://127.0.0.1:8000/test/',
                     data={
     'k1': 'v1', 'k2': 'v2'},
                     cookies={
     'cook1': 'value1'},
                     )
    #      CookieJar(             )
    from http.cookiejar import CookieJar
    from http.cookiejar import Cookie

    obj = CookieJar()
    obj.set_cookie(Cookie(version=0, name='c1', value='v1', port=None, domain='', path='/', secure=False, expires=None,
                          discard=True, comment=None, comment_url=None, rest={
     'HttpOnly': None}, rfc2109=False,
                          port_specified=False, domain_specified=False, domain_initial_dot=False, path_specified=False)
                   )
    requests.request(method='POST',
                     url='http://127.0.0.1:8000/test/',
                     data={
     'k1': 'v1', 'k2': 'v2'},
                     cookies=obj)


def param_files():
    #     
    # file_dict = {
     
    # 'f1': open('readme', 'rb')
    # }
    # requests.request(method='POST',
    # url='http://127.0.0.1:8000/test/',
    # files=file_dict)

    #     ,     
    # file_dict = {
     
    # 'f1': ('test.txt', open('readme', 'rb'))
    # }
    # requests.request(method='POST',
    # url='http://127.0.0.1:8000/test/',
    # files=file_dict)

    #     ,     
    # file_dict = {
     
    # 'f1': ('test.txt', "hahsfaksfa9kasdjflaksdjf")
    # }
    # requests.request(method='POST',
    # url='http://127.0.0.1:8000/test/',
    # files=file_dict)

    #     ,     
    # file_dict = {
     
    #     'f1': ('test.txt', "hahsfaksfa9kasdjflaksdjf", 'application/text', {'k1': '0'})
    # }
    # requests.request(method='POST',
    #                  url='http://127.0.0.1:8000/test/',
    #                  files=file_dict)

    pass


def param_auth():
    from requests.auth import HTTPBasicAuth, HTTPDigestAuth

    ret = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('wupeiqi', 'sdfasdfasdf'))
    print(ret.text)

    # ret = requests.get('http://192.168.1.1',
    # auth=HTTPBasicAuth('admin', 'admin'))
    # ret.encoding = 'gbk'
    # print(ret.text)

    # ret = requests.get('http://httpbin.org/digest-auth/auth/user/pass', auth=HTTPDigestAuth('user', 'pass'))
    # print(ret)
    #


def param_timeout():
    # ret = requests.get('http://google.com/', timeout=1)
    # print(ret)

    # ret = requests.get('http://google.com/', timeout=(5, 1))
    # print(ret)
    pass


def param_allow_redirects():
    ret = requests.get('http://127.0.0.1:8000/test/', allow_redirects=False)
    print(ret.text)


def param_proxies():
    # proxies = {
     
    # "http": "61.172.249.96:80",
    # "https": "http://61.185.219.126:3128",
    # }

    # proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}

    # ret = requests.get("http://www.proxy360.cn/Proxy", proxies=proxies)
    # print(ret.headers)


    # from requests.auth import HTTPProxyAuth
    #
    # proxyDict = {
     
    # 'http': '77.75.105.165',
    # 'https': '77.75.105.165'
    # }
    # auth = HTTPProxyAuth('username', 'mypassword')
    #
    # r = requests.get("http://www.google.com", proxies=proxyDict, auth=auth)
    # print(r.text)

    pass


def param_stream():
    ret = requests.get('http://127.0.0.1:8000/test/', stream=True)
    print(ret.content)
    ret.close()

    # from contextlib import closing
    # with closing(requests.get('http://httpbin.org/get', stream=True)) as r:
    # #       。
    # for i in r.iter_content():
    # print(i)


def requests_session():
    import requests

    session = requests.Session()

    ### 1、        ,  cookie

    i1 = session.get(url="http://dig.chouti.com/help/service")

    ### 2、    ,      cookie,   cookie   gpsd     
    i2 = session.post(
        url="http://dig.chouti.com/login",
        data={
     
            'phone': "8615131255089",
            'password': "xxxxxx",
            'oneMonth': ""
        }
    )

    i3 = session.post(
        url="http://dig.chouti.com/link/vote?linksId=8589623",
    )
    print(i3.text)
Jsonお願いします
#! /usr/bin/python3
import requests
import json


class url_request():
    def __init__(self):
        ''' init '''

if __name__ == '__main__':
    heard = {
     'Content-Type': 'application/json'}
    payload = {
     'CountryName': '  ',
               'ProvinceName': '   ',
               'L1CityName': 'chengdu',
               'L2CityName': 'yibing',
               'TownName': '',
               'Longitude': '107.33393',
               'Latitude': '33.157131',
               'Language': 'CN'}
    r = requests.post("http://www.xxxxxx.com/CityLocation/json/LBSLocateCity", heards=heard, data=payload)
    data = r.json()
    if r.status_code!=200:
        print('LBSLocateCity API Error' + str(r.status_code))
    print(data['CityEntities'][0]['CityID'])  #     json    key value
    print(data['ResponseStatus']['Ack'])
    print(json.dump(data, indent=4, sort_keys=True, ensure_ascii=False))  #     json,ensure_ascii    False        unicode
Xmlお願いします
#! /usr/bin/python3
import requests

class url_request():
    def __init__(self):
        """init"""

if __name__ == '__main__':
    heards = {
     'Content-type': 'text/xml'}
    XML = 'WeChatJSTicket.JobWS.Job.JobRefreshTicket,WeChatJSTicket.JobWSRUN1127.0.0.11false'
    url = 'http://jobws.push.mobile.xxxxxxxx.com/RefreshWeiXInTokenJob/RefreshService.asmx'
    r = requests.post(url=url, heards=heards, data=XML)
    data = r.text
    print(data)
状態異常処理
import requests

URL = 'http://ip.taobao.com/service/getIpInfo.php'  #   IP   API
try:
    r = requests.get(URL, params={
     'ip': '8.8.8.8'}, timeout=1)
    r.raise_for_status()  #           200,       
except requests.RequestException as e:
    print(e)
else:
    result = r.json()
    print(type(result), result, sep='
'
)
ファイルをアップロード
requestモジュールを使ってファイルをアップロードすることもできます。ファイルの種類は自動的に処理されます。
import requests
 
url = 'http://127.0.0.1:8080/upload'
files = {
     'file': open('/home/rxf/test.jpg', 'rb')}
#files = {'file': ('report.jpg', open('/home/lyb/sjzl.mpg', 'rb'))}     #        
 
r = requests.post(url, files=files)
print(r.text)
requestより便利なのは、文字列をファイルとしてアップロードすることができます。
import requests
 
url = 'http://127.0.0.1:8080/upload'
files = {
     'file': ('test.txt', b'Hello Requests.')}     #          
 
r = requests.post(url, files=files)
print(r.text)
認証
基本的なアイデンティティ認証(HTTP Baic Auth)
import requests
from requests.auth import HTTPBasicAuth
 
r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=HTTPBasicAuth('user', 'passwd'))
# r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=('user', 'passwd'))    #   
print(r.json())
もう一つの非常に人気のあるHTTP身分認証形式は要約型の身分認証であり、Requestsのサポートも開梱しています。
requests.get(URL, auth=HTTPDigestAuth('user', 'pass')
Cookiesと会話の対象
ある応答にいくつかのCookieが含まれている場合、それらに素早くアクセスできます。
import requests
 
r = requests.get('http://www.google.com.hk/')
print(r.cookies['NID'])
print(tuple(r.cookies))
あなたのcookiesをサーバーに送るには、cookiesパラメータが使えます。
import requests
 
url = 'http://httpbin.org/cookies'
cookies = {
     'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'}
#  Cookie Version 0     、   、   、   、  、   、  、  、@,  ,            Cookie   。
r = requests.get(url, cookies=cookies)
print(r.json())
セッションオブジェクトは、要求にまたがっていくつかのパラメータを保持することができます。最も便利なのは、同じSessionインスタンスに発行されたすべての要求の間でcookiesを維持し、これらは自動的に処理され、非常に便利です。次は本当の例を紹介します。次のように速盤で脚本にサインします。
import requests
 
headers = {
     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
           'Accept-Encoding': 'gzip, deflate, compress',
           'Accept-Language': 'en-us;q=0.5,en;q=0.3',
           'Cache-Control': 'max-age=0',
           'Connection': 'keep-alive',
           'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}
 
s = requests.Session()
s.headers.update(headers)
# s.auth = ('superuser', '123')
s.get('https://www.kuaipan.cn/account_login.htm')
 
_URL = 'http://www.kuaipan.cn/index.php'
s.post(_URL, params={
     'ac':'account', 'op':'login'},
       data={
     'username':'****@foxmail.com', 'userpwd':'********', 'isajax':'yes'})
r = s.get(_URL, params={
     'ac':'zone', 'op':'taskdetail'})
print(r.json())
s.get(_URL, params={
     'ac':'common', 'op':'usersign'})
requestsモジュールは、ウェブページのソースをキャプチャし、ファイルの例に保存します。
これは基本的なファイル保存操作ですが、ここでいくつかの注意すべき問題があります。
  • requestsパッケージをインストールし、コマンドラインにpip install requestsを入力すれば自動的にインストールできます。多くの人がrequestsを使うことを勧めています。自分の持っているurllib.requestもホームページのソースコードをつかむことができます。
  • openメソッドencodingパラメータをutf-8に設定します。保存されているファイルに文字化けが発生します。
  • キャプチャされたコンテンツを直接cmdに出力すると、各種の符号化エラーが発生しますので、ファイルビューに保存します。
  • with open方法は、より良い書き方であり、自動操作が完了したら、リソースを解放することができます。
    #! /urs/bin/python3
    import requests
    
    '''requests                '''
    html = requests.get("http://www.baidu.com")
    with open('test.txt', 'w', encoding='utf-8') as f:
        f.write(html.text)
        
    '''    txt  ,      ,       txt      '''
    ff = open('testt.txt', 'w', encoding='utf-8')
    with open('test.txt', encoding="utf-8") as f:
        for line in f:
            ff.write(line)
            ff.close()
    
    コマンドラインで1ライン分のデータを印刷すると、中国語では符号化エラーが発生しますので、1ラインずつ読み取り、別のファイルに保存します。これで読み取りが正常かどうかをテストします。(openに注意するときはエンコーディング方式を作る)
    自動ログインの例:
  • 自動ログイン「例:
  • * #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import requests
    
    
    # ##############     ##############
    """
    # ## 1、        ,  cookie
    i1 = requests.get(url="http://dig.chouti.com/help/service")
    i1_cookies = i1.cookies.get_dict()
    
    # ## 2、    ,      cookie,   cookie   gpsd     
    i2 = requests.post(
        url="http://dig.chouti.com/login",
        data={
            'phone': "8615131255089",
            'password': "xxooxxoo",
            'oneMonth': ""
        },
        cookies=i1_cookies
    )
    
    # ## 3、  (           gpsd  )
    gpsd = i1_cookies['gpsd']
    i3 = requests.post(
        url="http://dig.chouti.com/link/vote?linksId=8589523",
        cookies={'gpsd': gpsd}
    )
    
    print(i3.text)
    """
    
    
    # ##############     ##############
    """
    import requests
    
    session = requests.Session()
    i1 = session.get(url="http://dig.chouti.com/help/service")
    i2 = session.post(
        url="http://dig.chouti.com/login",
        data={
            'phone': "8615131255089",
            'password': "xxooxxoo",
            'oneMonth': ""
        }
    )
    i3 = session.post(
        url="http://dig.chouti.com/link/vote?linksId=8589523"
    )
    print(i3.text)
    
    """
    
  • ギthb
  • #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    import requests
    from bs4 import BeautifulSoup
    
    # ##############     ##############
    #
    # # 1.       ,   authenticity_token
    # i1 = requests.get('https://github.com/login')
    # soup1 = BeautifulSoup(i1.text, features='lxml')
    # tag = soup1.find(name='input', attrs={'name': 'authenticity_token'})
    # authenticity_token = tag.get('value')
    # c1 = i1.cookies.get_dict()
    # i1.close()
    #
    # # 1.   authenticity_token         ,      
    # form_data = {
         
    # "authenticity_token": authenticity_token,
    #     "utf8": "",
    #     "commit": "Sign in",
    #     "login": "[email protected]",
    #     'password': 'xxoo'
    # }
    #
    # i2 = requests.post('https://github.com/session', data=form_data, cookies=c1)
    # c2 = i2.cookies.get_dict()
    # c1.update(c2)
    # i3 = requests.get('https://github.com/settings/repositories', cookies=c1)
    #
    # soup3 = BeautifulSoup(i3.text, features='lxml')
    # list_group = soup3.find(name='div', class_='listgroup')
    #
    # from bs4.element import Tag
    #
    # for child in list_group.children:
    #     if isinstance(child, Tag):
    #         project_tag = child.find(name='a', class_='mr-1')
    #         size_tag = child.find(name='small')
    #         temp = "  :%s(%s);     :%s" % (project_tag.get('href'), size_tag.string, project_tag.string, )
    #         print(temp)
    
    
    
    # ##############     ##############
    # session = requests.Session()
    # # 1.       ,   authenticity_token
    # i1 = session.get('https://github.com/login')
    # soup1 = BeautifulSoup(i1.text, features='lxml')
    # tag = soup1.find(name='input', attrs={'name': 'authenticity_token'})
    # authenticity_token = tag.get('value')
    # c1 = i1.cookies.get_dict()
    # i1.close()
    #
    # # 1.   authenticity_token         ,      
    # form_data = {
         
    #     "authenticity_token": authenticity_token,
    #     "utf8": "",
    #     "commit": "Sign in",
    #     "login": "[email protected]",
    #     'password': 'xxoo'
    # }
    #
    # i2 = session.post('https://github.com/session', data=form_data)
    # c2 = i2.cookies.get_dict()
    # c1.update(c2)
    # i3 = session.get('https://github.com/settings/repositories')
    #
    # soup3 = BeautifulSoup(i3.text, features='lxml')
    # list_group = soup3.find(name='div', class_='listgroup')
    #
    # from bs4.element import Tag
    #
    # for child in list_group.children:
    #     if isinstance(child, Tag):
    #         project_tag = child.find(name='a', class_='mr-1')
    #         size_tag = child.find(name='small')
    #         temp = "  :%s(%s);     :%s" % (project_tag.get('href'), size_tag.string, project_tag.string, )
    #         print(temp)
    
  • 知乎
  • 
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import time
    
    import requests
    from bs4 import BeautifulSoup
    
    session = requests.Session()
    
    i1 = session.get(
        url='https://www.zhihu.com/#signin',
        headers={
         
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',
        }
    )
    
    soup1 = BeautifulSoup(i1.text, 'lxml')
    xsrf_tag = soup1.find(name='input', attrs={
         'name': '_xsrf'})
    xsrf = xsrf_tag.get('value')
    
    current_time = time.time()
    i2 = session.get(
        url='https://www.zhihu.com/captcha.gif',
        params={
         'r': current_time, 'type': 'login'},
        headers={
         
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',
        })
    
    with open('zhihu.gif', 'wb') as f:
        f.write(i2.content)
    
    captcha = input('   zhihu.gif  ,        :')
    form_data = {
         
        "_xsrf": xsrf,
        'password': 'xxooxxoo',
        "captcha": 'captcha',
        'email': '[email protected]'
    }
    i3 = session.post(
        url='https://www.zhihu.com/login/email',
        data=form_data,
        headers={
         
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',
        }
    )
    
    i4 = session.get(
        url='https://www.zhihu.com/settings/profile',
        headers={
         
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',
        }
    )
    
    soup4 = BeautifulSoup(i4.text, 'lxml')
    tag = soup4.find(id='rename-section')
    nick_name = tag.find('span',class_='name').string
    print(nick_name)
    
  • ブログパーク
  • #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import re
    import json
    import base64
    
    import rsa
    import requests
    
    
    def js_encrypt(text):
        b64der = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCp0wHYbg/NOPO3nzMD3dndwS0MccuMeXCHgVlGOoYyFwLdS24Im2e7YyhB0wrUsyYf0/nhzCzBK8ZC9eCWqd0aHbdgOQT6CuFQBMjbyGYvlVYU2ZP7kG9Ft6YV6oc9ambuO7nPZh+bvXH0zDKfi02prknrScAKC0XhadTHT3Al0QIDAQAB'
        der = base64.standard_b64decode(b64der)
    
        pk = rsa.PublicKey.load_pkcs1_openssl_der(der)
        v1 = rsa.encrypt(bytes(text, 'utf8'), pk)
        value = base64.encodebytes(v1).replace(b'
    '
    , b'') value = value.decode('utf8') return value session = requests.Session() i1 = session.get('https://passport.cnblogs.com/user/signin') rep = re.compile("'VerificationToken': '(.*)'") v = re.search(rep, i1.text) verification_token = v.group(1) form_data = { 'input1': js_encrypt('wptawy'), 'input2': js_encrypt('asdfasdf'), 'remember': False } i2 = session.post(url='https://passport.cnblogs.com/user/signin', data=json.dumps(form_data), headers={ 'Content-Type': 'application/json; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'VerificationToken': verification_token} ) i3 = session.get(url='https://i.cnblogs.com/EditDiary.aspx') print(i3.text)
  • 指切りネット
  • #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    import requests
    
    
    #    :     ,  X_Anti_Forge_Token,X_Anti_Forge_Code
    # 1、  url:https://passport.lagou.com/login/login.html
    # 2、    :GET
    # 3、   :
    #    User-agent
    r1 = requests.get('https://passport.lagou.com/login/login.html',
                     headers={
         
                         'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
                     },
                     )
    
    X_Anti_Forge_Token = re.findall("X_Anti_Forge_Token = '(.*?)'", r1.text, re.S)[0]
    X_Anti_Forge_Code = re.findall("X_Anti_Forge_Code = '(.*?)'", r1.text, re.S)[0]
    print(X_Anti_Forge_Token, X_Anti_Forge_Code)
    # print(r1.cookies.get_dict())
    #    :  
    # 1、  url:https://passport.lagou.com/login/login.json
    # 2、    :POST
    # 3、   :
    #    cookie
    #    User-agent
    #    Referer:https://passport.lagou.com/login/login.html
    #    X-Anit-Forge-Code:53165984
    #    X-Anit-Forge-Token:3b6a2f62-80f0-428b-8efb-ef72fc100d78
    #    X-Requested-With:XMLHttpRequest
    # 4、   :
    # isValidate:true
    # username:15131252215
    # password:ab18d270d7126ea65915c50288c22c0d
    # request_form_verifyCode:''
    # submit:''
    r2 = requests.post(
        'https://passport.lagou.com/login/login.json',
        headers={
         
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
            'Referer': 'https://passport.lagou.com/login/login.html',
            'X-Anit-Forge-Code': X_Anti_Forge_Code,
            'X-Anit-Forge-Token': X_Anti_Forge_Token,
            'X-Requested-With': 'XMLHttpRequest'
        },
        data={
         
            "isValidate": True,
            'username': '15131255089',
            'password': 'ab18d270d7126ea65915c50288c22c0d',
            'request_form_verifyCode': '',
            'submit': ''
        },
        cookies=r1.cookies.get_dict()
    )
    print(r2.text)
    
    参考:http://cn.python-requests.org/zh_CN/latest/user/quickstart.http://www.python-requests.org/en/master/ http://docs.python-requests.org/en/latest/user/quickstart/ https://www.cnblogs.com/tangdongchu/p/4229049.html#t0 http://www.cnblogs.com/wupeiqi/articles/6283017.html
    転載先:https://www.cnblogs.com/lanyinhao/p/9634742.html