python爬蟲基礎(chǔ)教程:requests庫(二)代碼實例
更新時間:2019年04月09日 16:50:45 作者:嗨學(xué)編程
這篇文章主要介紹了python爬蟲基礎(chǔ)教程:requests庫(二),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
get請求
簡單使用
import requests
'''
想要學(xué)習(xí)Python?Python學(xué)習(xí)交流群:973783996滿足你的需求,資料都已經(jīng)上傳群文件,可以自行下載!
'''
response = requests.get("https://www.baidu.com/")
#text返回的是unicode的字符串,可能會出現(xiàn)亂碼情況
# print(response.text)
#content返回的是字節(jié),需要解碼
print(response.content.decode('utf-8'))
# print(response.url) #https://www.baidu.com/
# print(response.status_code) #200
# print(response.encoding) #ISO-8859-1
添加headers和params
import requests
params = {
'wd':'python'
}
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36'
}
response = requests.get("https://www.baidu.com/s",params=params,headers=headers)
#content返回的是字節(jié),需要解碼
with open('baidu.html','w',encoding='utf-8') as f:
f.write(response.content.decode('utf-8'))
POST請求
爬去拉鉤網(wǎng)職位信息
import requests
url = "https://www.lagou.com/jobs/positionAjax.json?city=%E5%8C%97%E4%BA%AC&needAddtionalResult=false"
data = {
'first':'true',
'pn':1,
'kd':'python'
}
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36",
"Referer":"https://www.lagou.com/jobs/list_python?city=%E5%8C%97%E4%BA%AC&cl=false&fromSearch=true&labelWords=&suginput="
}
response = requests.post(url,data=data,headers=headers)
# print(response.text)
print(type(response.text)) #<class 'str'>
print(type(response.json())) #<class 'dict'>
print(response.json()) #獲取為字典的形式
使用代理
import requests
proxy = {'http':'115.210.31.236.55:9000'}
response = requests.get("https://www.baidu.com/",proxies=proxy)
print(response.content.decode('utf-8'))
session登錄
# _*_ coding:utf-8 _*_
import requests
# 1. 創(chuàng)建session對象,可以保存Cookie值
ssion = requests.session()
# 2. 處理 headers
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'}
# 3. 需要登錄的用戶名和密碼
data = {"email":"158xxxxxxxx", "password":"pythonxxxxxxx"}
# 4. 發(fā)送附帶用戶名和密碼的請求,并獲取登錄后的Cookie值,保存在ssion里
ssion.post("http://www.renren.com/PLogin.do", data = data)
# 5. ssion包含用戶登錄后的Cookie值,可以直接訪問那些登錄后才可以訪問的頁面
response = ssion.get("http://zhibo.renren.com/news/108")
# 6. 打印響應(yīng)內(nèi)容
print(response.text)
以上所述是小編給大家介紹的python爬蟲基礎(chǔ)教程:requests庫(二)詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Python數(shù)據(jù)分析pandas模塊用法實例詳解
這篇文章主要介紹了Python數(shù)據(jù)分析pandas模塊用法,結(jié)合實例形式分析了pandas模塊對象創(chuàng)建、數(shù)值運算等相關(guān)操作技巧與注意事項,需要的朋友可以參考下2019-11-11
python之線程池map()方法傳遞多參數(shù)list
這篇文章主要介紹了python之線程池map()方法傳遞多參數(shù)list問題,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
Python標(biāo)準(zhǔn)庫筆記struct模塊的使用
這篇文章主要介紹了Python標(biāo)準(zhǔn)庫筆記struct模塊的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02

