ITPub博客

首页 > IT职业 > IT生活 > python爬虫实战:request如何定义headers

python爬虫实战:request如何定义headers

IT生活 作者:ebrain68 时间:2021-09-11 10:07:45 0 删除 编辑

都说知识之间是相互汇通和包容的,借着我们之前才讲过header的热乎劲,为大家带来新朋友request的同时,也不忘记再来跟我们的老朋友header见见面。说到这里已经有小伙伴开始好奇,request会定义headers呢?简单的来说就是request帮助header进行网页访问,接下来看看是如何进行的吧。


对于写爬虫来讲,模拟浏览器是发请求的时候做的最多的事情了,最常见的模拟浏览器无非就是伪装headers:

In [23]: url = 'http://xlzd.me'
 
In [24]: headers = {'User-Agent': 'my custom user agent', 'Cookie': 'haha'}
 
In [25]: requests.get(url, headers=headers)

 

拓展:

怎样取出HTTP response里面的内容呢?

In [7]: r = requests.get('http://xlzd.me')
 
In [8]: r.encoding
Out[8]: 'UTF-8'
 
In [9]: r.headers
Out[9]: {'Content-Encoding': 'gzip', 'Transfer-Encoding': 'chunked', 'Vary': 'Accept-Encoding', 'Server': 'nginx', 'Connection': 'keep-alive', 'Date': 'Fri, 11 Dec 2015 06:42:31 GMT', 'Content-Type': 'text/html; charset=UTF-8', 'X-Pingback': 'http://xlzd.me/action/xmlrpc'}
 
In [10]: r.cookies
Out[10]: <RequestsCookieJar[]>
 
In [11]: r.text
Out[11]: u'<!DOCTYPE HTML>n<html>nt<hea......

requests会自动对响应内容编码,所以就可以通过r.text取出响应文本了。对于别等响应内容(文件、图片、...),则可以通过r.content取出来。对于json内容,也可以通过r.json()来取。

本篇的借助request访问网页浏览的方法大家肯定都学会了,从代码上面看,算是最简单的一种。如果之间有其他方法没有学会的小伙伴,可以以后都使用request方法。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2920/viewspace-2832066/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: html转jsp
请登录后发表评论 登录
全部评论

注册时间:2019-08-13

  • 博文量
    68
  • 访问量
    449