python 爬蟲_Requests庫詳細用法


Requests庫詳細用法
1. 基於urllib的簡單的http庫
2. 實例

import requests
response=requests.get('http://www.xxx.com')
print(type(response))
print(response.status_code)
print(response.cookies)

3. 請求方式:

import requests
requests.post('網址')
data={    #添加參數,字典類型
'name':'spencer', 'age':28
}
response=requests.get('網址', params=data)

 


4. 解析json:

response=requests.get('http://www.xxx.com')
        print(response.json())
        print(json.loads(response.text))

5. 獲取二級制數據

        response=requests.get('http://www.xxx.com/xxx/ico')
        print(response.content)    #打印二進制內容
        with open('圖標名稱','wb') as f  #設置圖標參數
            f.write(response.content) #保存圖標

 


6. 添加headers: 

import requests
        headers={
        'user-agent':'xnxnxnxxnxnxxnxnxnxnxxn' #添加自己的主機名
        }
        response=requests.get('http://www.xxx.com',headers=headers)

 

7.文件上傳:

files={"file": open('文件名'"rb")}
response=requests.post('上傳的地址', files=files)
print(response.text)

 


8. 獲取cookies

response=requests.get('http://www.xxx.com')
        print(response.cookies)
        for key, value in response.cookies.items():
            print(key+'='+value)

9.會話維持:模擬登陸

s=requests.Session()
        s.get('http//xxx.com/cookies/set/number/123456')
        response=s.get('http://xxx.com/cookies')
        print(response.text)

10. 證書驗證
  response=requests.get('http://www.xxx.com',verify=False)
11. 代理設置:

import requests
        proxies={
            'http':'http//xxx'
            'https':'https://xxx'
        }
        response=requests.get('http://www.xxx.com',proxies=proxies)

12. 超時設置:

from requests.exceptions import ReadTimeout
        try        #超出時間設置
            response=requests.get('http://www.xxx.com',timeout=1)
        except ReadTimeout
            print('timeout')     #超出時間的打印timeout

 


13.認證設置:
  response=requests.get('http://www.xxx.com',auth=('user','123'))
14.異常處理:

try        #處理異常
            response=requests.get('http://www.xxx.com',timeout=1)
        except ReadTimeout
        

 



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM