python爬虫 基于requests模块的get请求实现详解
需求:爬取搜狗首页的页面数据
importrequests #1.指定url url='https://www.sogou.com/' #2.发起get请求:get方法会返回请求成功的响应对象 response=requests.get(url=url) #3.获取响应中的数据:text属性作用是可以获取响应对象中字符串形式的页面数据 page_data=response.text #4.持久化数据 withopen("sougou.html","w",encoding="utf-8")asf: f.write(page_data) f.close() print("ok")
requests模块如何处理携带参数的get请求,返回携带参数的请求
需求:指定一个词条,获取搜狗搜索结果所对应的页面数据
之前urllib模块处理url上参数有中文的需要处理编码,requests会自动处理url编码
发起带参数的get请求
params可以是传字典或者列表
defget(url,params=None,**kwargs): r"""SendsaGETrequest. :paramurl:URLforthenew:class:`Request`object. :paramparams:(optional)Dictionary,listoftuplesorbytestosend inthebodyofthe:class:`Request`. :param\*\*kwargs:Optionalargumentsthat``request``takes. :return::class:`Response`object :rtype:requests.Response
importrequests #指定url url='https://www.sogou.com/web' #封装get请求参数 prams={ 'query':'周杰伦', 'ie':'utf-8' } response=requests.get(url=url,params=prams) page_text=response.text withopen("周杰伦.html","w",encoding="utf-8")asf: f.write(page_text) f.close() print("ok")
利用requests模块自定义请求头信息,并且发起带参数的get请求
get方法有个headers参数把请求头信息的字典赋给headers参数
importrequests #指定url url='https://www.sogou.com/web' #封装get请求参数 prams={ 'query':'周杰伦', 'ie':'utf-8' } #自定义请求头信息 headers={ 'User-Agent':'Mozilla/5.0(Macintosh;IntelMacOSX10_12_0)AppleWebKit/537.36(KHTML,likeGecko)Chrome/69.0.3497.100Safari/537.36', } response=requests.get(url=url,params=prams,headers=headers) page_text=response.text withopen("周杰伦.html","w",encoding="utf-8")asf: f.write(page_text) f.close() print("ok")
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。