爬虫類urllib、requestsの使い方

5763 ワード

urllibの使い方
from urllib import request
from urllib import parse
import json


url = 'http://top.hengyan.com/dianji/default.aspx?p=1'
#      
headers = {
     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3722.400 QQBrowser/10.5.3738.400'
}
 """
 url :  url
 data=None  :   None   get  ,    None   get  
 timeout:         
 cafile=None, capath=None, cadefault=False:      
 context=None :      
 """
 # url       
 response = request.urlopen(url=url, timeout=10)

#      
req = request.Request(url=url, headers=headers)
response = request.urlopen(req, timeout=10)

code = response.status
url = response.url
b_content = response.read()

html = b_content.decode('utf-8')

#     
with open('hengyan.html', 'w') as file:
   file.write(html)


#####################post  #############################
#      
def get_ssjy_data(page=1):
    url = 'http://search.jiayuan.com/v2/search_v2.php'
    #      
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3722.400 QQBrowser/10.5.3738.400'
    }

    form_data = {
        'sex': 'f',
        'key': '',
        'stc': '1:11,2:20.28,23:1',
        'sn': 'default',
        'sv': '1',
        'p': str(page),
        'f': 'search',
        'listStyle': 'bigPhoto',
        'pri_uid': '0',
        'jsversion': 'v5',
    }

    form_data = parse.urlencode(form_data).encode('utf-8')

    #       
    req = request.Request(url=url, data=form_data, headers=headers)
    response = request.urlopen(req, timeout=10)
    if response.status == 200:
        content = response.read().decode('utf-8').replace('##jiayser##//', '').replace('##jiayser##', '')
        data = json.loads(content)
        userinfos = data['userInfo']
        for user in userinfos:
            age = user['age']
            name = user['nickname']
            gender = user['sex']

        #      
        total_page = int(data['pageTotal'])
        print(str(page) + '     ')
        if page < total_page:
            #          
            next_page = page + 1
            #      ,         
            get_ssjy_data(page=next_page)
        else:
            #       
            print('      ')


if __name__ == '__main__':
    get_ssjy_data()

requestsの使い方
一、何がrequestsですか?
  • requestsは、urllibの再パッケージに基づいて、urllibのすべての特性を持ち、API呼び出しがより便利であり、ネットワーク要求に基づくモジュールであり、ブラウザ開始要求
  • をシミュレートする。
    二、なぜrequestsモジュールを使用しますか?
  • 1.自動処理url符号
  • .自動処理post要求パラメータ
  • .クッキーとエージェントの動作を簡略化する。
  • クッキーの動作:
  • a.cookiejarオブジェクトを作成する
  • b.handlerオブジェクトを作成する
  • c.openerオブジェクトを作成する
  • エージェントの動作:
  • a.handlerオブジェクトを作成し、プロキシipとポートをこのオブジェクト
  • にカプセル化する。
  • b.openerオブジェクトを作成する
  • 三、どうやってインストールしますか?
    インストール:pip 3 install requests
    使用プロセス:
    1.  url
    2.  requests      
    3.          
    4.       
    
    requestsは5中の要求を含みます。get、post、ajaxのget要求、ajaxのpost要求、総合的に。
    requestsのget要求
    url = 'http://top.hengyan.com/dianji/default.aspx?'
    
    #  get          
    params = {
        'p': 1
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
    }
    response = requests.get(url=url, headers=headers, params=params)
    #   html    
    html = response.text
    #           
    b_content = response.content
    #         
    code = response.status_code
    #         
    response_headers = response.headers
    #      url  
    url = response.url
    
    #   cookies  (  requests         cookies)
    cookies = response.cookies
    #  RequestsCookieJar     
    cookies_dict = requests.utils.dict_from_cookiejar(cookies)
    #       RequestsCookieJar
    cookiesjar_obj = requests.utils.cookiejar_from_dict(cookies_dict)
    
    requestsのpostの使い方
    url = 'http://search.jiayuan.com/v2/search_v2.php'
    #      
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3722.400 QQBrowser/10.5.3738.400'
    }
    
    form_data = {
        'sex': 'f',
        'key': '',
        'stc': '1:11,2:20.28,23:1',
        'sn': 'default',
        'sv': '1',
        'p': '1',
        'f': 'search',
        'listStyle': 'bigPhoto',
        'pri_uid': '0',
        'jsversion': 'v5',
    }
    response = requests.post(url=url, data=form_data, headers=headers)
    
    if response.status_code == 200:
        pattern = re.compile('##jiayser##(.*?)##jiayser//', re.S)
        json_str = re.findall(pattern=pattern, string=response.text)[0]
        json_data = json.loads(json_str)
    
    カスタム要求ヘッダ情報:
    from fake_useragent import UserAgent
         
    headers ={
    	"User-Agent":UserAgent().random
    }
    
    パッケージget要求パラメータ:
    params = {
    	"   ":"  "
    }
    
    requestsライブラリにおけるsessionの役割:
  • は、統一セッションを維持し、アクセスを要求する際に、いくつかの情報(例えば、cookies)
  • を保存することができる。
    クッキー:
    1.         
    2.  :  xx             
    
    クッキー役割:サービス側はクッキーを使用してクライアントの状態情報を記録します。
    実現プロセス:
  • 1.登録操作(cookieを取得)を実行する
  • .個人のホームページ要求を開始するには、クッキーをこの要求に携帯する必要がある
  • 注意:sessionオブジェクト:送信要求(cookieオブジェクトを自動記憶する)