需求:爬取搜狗首頁的頁面數據
import requests # 1.指定url url = 'https://www.sogou.com/' # 2.發起get請求:get方法會返回請求成功的響應對象 response = requests.get(url=url) # 3.獲取響應中的數據:text屬性作用是可以獲取響應對象中字符串形式的頁面數據 page_data = response.text # 4.持久化數據 with open("sougou.html","w",encoding="utf-8") as f: f.write(page_data) f.close() print("ok")
requests模塊如何處理攜帶參數的get請求,返回攜帶參數的請求
需求:指定一個詞條,獲取搜狗搜索結果所對應的頁面數據
之前urllib模塊處理url上參數有中文的需要處理編碼,requests會自動處理url編碼
發起帶參數的get請求
params可以是傳字典或者列表
def get(url, params=None, **kwargs): r"""Sends a GET request. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary, list of tuples or bytes to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response` object :rtype: requests.Response
import requests # 指定url url = 'https://www.sogou.com/web' # 封裝get請求參數 prams = { 'query':'周杰倫', 'ie':'utf-8' } response = requests.get(url=url,params=prams) page_text = response.text with open("周杰倫.html","w",encoding="utf-8") as f: f.write(page_text) f.close() print("ok")
利用requests模塊自定義請求頭信息,并且發起帶參數的get請求
get方法有個headers參數 把請求頭信息的字典賦給headers參數
import requests # 指定url url = 'https://www.sogou.com/web' # 封裝get請求參數 prams = { 'query':'周杰倫', 'ie':'utf-8' } # 自定義請求頭信息 headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36', } response = requests.get(url=url,params=prams,headers=headers) page_text = response.text with open("周杰倫.html","w",encoding="utf-8") as f: f.write(page_text) f.close() print("ok")
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
