Skip to content
Python:Requests 模組
📆2018-08-26 | 📂Data Science

Install

shell
$pip3 install requests

Get

範例程式為對網頁做基本請求&接收回應,raise_for_status()為return檢查,若返回異常則拋出error

python
import requests as rq

url = 'http://www.google.com.tw/search?'  # target url
try:
    res = rq.get(url)
    res.raise_for_status()
except rq.HTTPError:
    print('HTTP Error!')

print(res.text)  # html

Payload

必要時可以加上參數,例如Google Search:

python
payload = {'q':'data science'}
res = rq.get(url, params=payload)  # http://www.google.com.tw/search?q=data+science

*參數的部分為字典結構,key則視url結構而定

Post

針對網頁中的表單,可以使用Post來傳送Payload

python
res = rq.post(url, params=payload)

但...對Google Search頁面做Post會得到這樣的回應:

html
<a href=//www.google.com/><span id=logo aria-label=Google></span></a>
<p><b>405.</b> <ins>That’s an error.</ins>
<p>The request method <code>POST</code> is inappropriate for the URL <code>/search?q=data+science</code>.  
<ins>That’s all we know.</ins>

Google說這樣是不當的行為呢,我只是做個示範,好孩子不要學呀^.<

Last updated: