溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python爬蟲基礎(chǔ)教程:requests庫(kù)(二)代碼實(shí)例

發(fā)布時(shí)間:2020-08-28 06:00:31 來(lái)源:腳本之家 閱讀:150 作者:嗨學(xué)編程 欄目:開發(fā)技術(shù)

get請(qǐng)求

簡(jiǎn)單使用

import requests
'''
想要學(xué)習(xí)Python?Python學(xué)習(xí)交流群:973783996滿足你的需求,資料都已經(jīng)上傳群文件,可以自行下載!
'''
response = requests.get("https://www.baidu.com/")
#text返回的是unicode的字符串,可能會(huì)出現(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請(qǐng)求

爬去拉鉤網(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對(duì)象,可以保存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ā)送附帶用戶名和密碼的請(qǐng)求,并獲取登錄后的Cookie值,保存在ssion里
ssion.post("http://www.renren.com/PLogin.do", data = data)
 
# 5. ssion包含用戶登錄后的Cookie值,可以直接訪問(wèn)那些登錄后才可以訪問(wèn)的頁(yè)面
response = ssion.get("http://zhibo.renren.com/news/108")
 
# 6. 打印響應(yīng)內(nèi)容
print(response.text)
 

以上所述是小編給大家介紹的python爬蟲基礎(chǔ)教程:requests庫(kù)(二)詳解整合,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI