15.python爬虫—Requests

15.1 网络爬虫基础知识

  • 网络爬虫概述
    • 网络爬虫是一个自动提取网页的程序,模拟客户端发送网络请求,接收请求响应,一种按照一定的规则,自动地抓取互联网信息的程序。
  • 网络爬虫分类
    • 批量型爬虫
      • 批量型爬虫有明确的抓取范围和目标,当爬虫达到这个设定的目标后,即停止抓取过程。
    • 增量型爬虫
      • 增量型爬虫会持续不断的抓取,对于抓取的网页,要定期更新。通用的商业搜索引擎爬虫基本都属于此类。
    • 垂直型爬虫
      • 垂直型爬虫关注特定主题内容或者属于特定行业的网页,其他主题或者其他行业的内容不再考虑范围

15.2 爬虫结构

  • Robots协议:网站通过Robots协议告诉搜索引擎哪些页面可以抓取,哪 些页面不能抓取。

15.3 Http协议

  • HTTP协议(HyperText Transfer Protocol,超文本传输协议)
  • HTTP是一个基于TCP/IP通信协议来传递数据(HTML 文件, 图片文件, 查询结果等)
  • HTTP是无连接
  • HTTP是媒体独立的
  • HTTP是无状态

15.4 Http头和主体

  • 一个http请求代表客户端浏览器向服务器发送的数据。一个完整的http请求消息,包含一个请求行,若干个消息头(请求头),换行,实体内容
  • 请求行:描述客户端的请求方式、请求资源的名称、http协议的版本号。 例如: GET/BOOK/JAVA.HTML HTTP/1.1
  • 请求头(消息头)包含(客户机请求的服务器主机名,客户机的环境信息等):
    • Accept:用于告诉服务器,客户机支持的数据类型 (例如:Accept:text/html,image/*)
    • Accept-Charset:用于告诉服务器,客户机采用的编码格式
    • Accept-Encoding:用于告诉服务器,客户机支持的数据压缩格
    • Accept-Language:客户机语言环境
    • Host:客户机通过这个服务器,想访问的主机名
    • If-Modified-Since:客户机通过这个头告诉服务器,资源的缓存时间
    • Referer:客户机通过这个头告诉服务器,它(客户端)是从哪个资源来访问服务器的(防盗链)
    • User-Agent:客户机通过这个头告诉服务器,客户机的软件环境(操作系统,浏览器版本等)
    • Cookie:客户机通过这个头,将Coockie信息带给服务器
    • Connection:告诉服务器,请求完成后,是否保持连接
    • Date:告诉服务器,当前请求的时间
  • 一个http响应代表服务器端向客户端回送的数据,它包括:
    • 一个状态行,若干个消息头,以及实体内容
  • 响应头(消息头)包含:
    • Location:这个头配合302状态吗,用于告诉客户端找谁
    • Server:服务器通过这个头,告诉浏览器服务器的类型
    • Content-Encoding:告诉浏览器,服务器的数据压缩格式
    • Content-Length:告诉浏览器,回送数据的长度
    • Content-Type:告诉浏览器,回送数据的类型
    • Last-Modified:告诉浏览器当前资源缓存时间
    • Refresh:告诉浏览器,隔多长时间刷新
    • Content-Disposition:告诉浏览器以下载的方式打开数据。例如:context.Response.AddHeader(“ContentDisposition”,“attachment:filename=aa.jpg”); context.Response.WriteFile(“aa.jpg”);
    • Transfer-Encoding:告诉浏览器,传送数据的编码格式
    • ETag:缓存相关的头(可以做到实时更新)
    • Expries:告诉浏览器回送的资源缓存多长时间。如果是-1或者0,表示不缓存
    • Cache-Control:控制浏览器不要缓存数据 no-cache
    • Pragma:控制浏览器不要缓存数据 no-cache
    • Connection:响应完成后,是否断开连接。 close/Keep-Alive
    • Date:告诉浏览器,服务器响应时间
    • 状态行: 例如: HTTP/1.1 200 OK (协议的版本号是1.1 响应状态码为200 响应结果为 OK)

15.5 Python中HttpRequest实现

  • Requests实现:是Python爬虫开发中最为常用的方式。Requests库是第三方模块,需要额外进行安装
    • pip
    • install
    • requests

In:

pip install requests

out:

Requirement already satisfied: requests in d:\programdata\anaconda3\lib\site-packages (2.22.0)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in d:\programdata\anaconda3\lib\site-packages (from requests) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in d:\programdata\anaconda3\lib\site-packages (from requests) (2019.9.11)
Requirement already satisfied: idna<2.9,>=2.5 in d:\programdata\anaconda3\lib\site-packages (from requests) (2.8)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in d:\programdata\anaconda3\lib\site-packages (from requests) (1.24.2)
Note: you may need to restart the kernel to use updated packages.

In:

import requests

In:

req = requests.get("https://www.baidu.com/")

In:

req

out:

<Response [200]>

In:

req.encoding='utf-8'

In:

req.text

out:

'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write(\'<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=\'+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ \'" name="tj_login" class="lb">登录</a>\');\r\n                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'

In:

req.content.decode('utf8')

out:

'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write(\'<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=\'+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ \'" name="tj_login" class="lb">登录</a>\');\r\n                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'

In:

req.request.headers #请求头

out:

{'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}

In:

req.request.headers.get('User-Agent')

out:

'python-requests/2.22.0'

In:

req.headers #响应头

out:

{'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Sat, 18 Jul 2020 06:30:06 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:23:51 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}

In:

#带请求头访问
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"}
req2 = requests.get("https://www.baidu.com/",headers=headers)

In:

req2.content.decode("utf8")

out:

'<!DOCTYPE html><!--STATUS OK-->\n\n\n    <html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta content="always" name="referrer"><meta name="theme-color" content="#2932e1"><meta name="description" content="全球最大的中文搜索引擎、致力于让网民更便捷地获取信息,找到所求。百度超过千亿的中文网页数据库,可以瞬间找到相关的搜索结果。">
......

In:

lis1 = [1,2,3]
for i in lis1:
    print(lis1.index(i))

out:

0
1
2

In:

for i,v in enumerate(lis1):
    print(i)

out:

0
1
2

In:

for key in req.cookies.keys():
    req.cookies.get(key)

人人网
In:

loginurl = 'http://www.renren.com/PLogin.do'
mainurl = 'http://www.renren.com/972470782'
pdata = {'email':'xxx','password':'xxx'}
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"}

In:

# reqrr = requests.get(url=mainurl,headers=headers)
# with open("renren.html","w",encoding='utf-8') as f:
#     f.write(reqrr.content.decode())

In:

ses = requests.session()
ses.post(url=loginurl,data=pdata,headers=headers)

out:

<Response [200]>

In:

reqrraf = ses.get(url=mainurl,headers=headers)
with open("renren2.html","w",encoding='utf-8') as f:
    f.write(reqrraf.content.decode())
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值