需求:爬取搜狗首頁的頁面數(shù)據(jù)
import requests
# 1.指定url
url = 'https://www.sogou.com/'
# 2.發(fā)起get請求:get方法會返回請求成功的響應(yīng)對象
response = requests.get(url=url)
# 3.獲取響應(yīng)中的數(shù)據(jù):text屬性作用是可以獲取響應(yīng)對象中字符串形式的頁面數(shù)據(jù)
page_data = response.text
# 4.持久化數(shù)據(jù)
with open("sougou.html","w",encoding="utf-8") as f:
f.write(page_data)
f.close()
print("ok")
requests模塊如何處理攜帶參數(shù)的get請求,返回攜帶參數(shù)的請求
需求:指定一個詞條,獲取搜狗搜索結(jié)果所對應(yīng)的頁面數(shù)據(jù)
之前urllib模塊處理url上參數(shù)有中文的需要處理編碼,requests會自動處理url編碼
發(fā)起帶參數(shù)的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請求參數(shù)
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模塊自定義請求頭信息,并且發(fā)起帶參數(shù)的get請求
get方法有個headers參數(shù) 把請求頭信息的字典賦給headers參數(shù)
import requests
# 指定url
url = 'https://www.sogou.com/web'
# 封裝get請求參數(shù)
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")
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

