[python爬虫之路dya3]: requests库的基本使用
前面我們學(xué)習(xí)了urllib庫進(jìn)行源代碼的爬取,今天來介紹更加人性化的requests庫的使用。
import requests '''response=requests.get("https://baidu.com/") print(response.text)#獲取源代碼方法1 print(response.content.decode("utf-8"))#獲取源代碼方法2****注意:****response.content是直接爬取的源代碼沒有經(jīng)過解碼的代碼,故是bytes類型,而response.text則是經(jīng)過requets庫自己的猜測進(jìn)行的解碼,有時(shí)可出現(xiàn)亂碼,所以此時(shí)應(yīng)該用response.content.decode(“utf-8”)
基本屬性:
‘’’
#get請求用params, post請求用data
注意:可以如此使用請求:
1.requests.get(“https://baidu.com/”)
2.requests.post(“https://baidu.com/”)
例子1:對于“百度一下#深圳#”的源代碼(get請求實(shí)例):
例子2:對于“拉鉤網(wǎng)#python#”的源代碼(get請求實(shí)例)
import requests data={"first": "true" , "pn": "1" , "kd": "python" } headers={"Referer":" https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36"} response=requests.post("https://www.lagou.com/jobs/positionAjax.json?city=%E6%B7%B1%E5%9C%B3&needAddtionalResult=false",data=data,headers=headers) print(response.json)****#response.json可以將json源代碼轉(zhuǎn)換成字典或者列表的形式。**** *requests庫使用代理IP*
import requests proxy={"HTTP":"114.226.246.144:9999"} response=requests.get("http://httpbin.org/ip",proxies=proxy) print(response.text)#此處本人在實(shí)現(xiàn)時(shí)發(fā)現(xiàn)一直無法成功代理,在確保代碼無誤之后覺得是使用免費(fèi)代理的緣故,所以此處應(yīng)多次嘗試更換代理IP或者使用有償ip
requests處理cookie信息
**如果在多次使用中共享cookie信息,那么應(yīng)該使用session**
url="http://www.renren.com/" data={"email":"135*********","password":"***08***"} headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36"} session=requests.session() session.post(url,data=data,headers=headers) response=session.get("http://www.renren.com/973687886/profile") with open("renren.html","w",encoding="utf-8") as fp:fp.write(response.text)`處理不信任的SSL證書:(爬取某些網(wǎng)頁無法進(jìn)入時(shí))
response=requests.get("http://*******",verify=False) print(response.content.decode("utf-8"))```
總結(jié)
以上是生活随笔為你收集整理的[python爬虫之路dya3]: requests库的基本使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CDN加速技术可以解决的问题——诺必达云
- 下一篇: excel文件怎么转成vcf_批量exc