Python實作爬蟲的檔案上傳、下載下傳,以及同一會話
(一)安裝requests子產品
對于python2,直接在指令行輸入
pip install requests
Python3的話,在指令行輸入
pip3 install requests
如果你使用的電腦隻使用了一個版本的Python程式的話,當然隻需要使用pip 的指令就好了
(二)Python代碼的實作
代碼如下所示
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}
def download_file(path): # 下載下傳檔案
r = requests.get("https://github.com/favicon.ico", headers=headers)
# print(r.text) # 擷取文本
# print(r.content) # 擷取源格式内容
with open(path, 'wb') as f:
f.write(r.content)
def upload_file(): # 上傳檔案
files = {'file': open('favicon.ico', 'rb')}
r = requests.post('http://httpbin.org/post', files=files, headers=headers)
print(r.text)
def practise_session(): # 爬蟲的會話(使用同一個會話的cookie)
s = requests.Session()
s.get('http://httpbin.org/cookies/set/number/123456789', headers=headers)
r = s.get('http://httpbin.org/cookies', headers=headers)
print(r.text)
if __name__ == '__main__':
# path = 'favicon.ico'
# download_file(path)
# upload_file()
practise_session()
參考連結:
Python3網絡爬蟲開發實戰