【Python爬虫】01

课程:Python网络爬虫与信息提取

目标:掌握定向网络数据爬取和网页解析的基本能力。

the website is the API

课程分为以下部分:

1、requsets库(自动爬取HTML页面、自动网络请求提交)

2、robots.txt规则(网络爬虫排除标准)(合理合法的使用爬虫)

3、beautiful soup库(解析HTML页面)(提取相关项目)

4、projects项目(实战项目A/B)

5、re正则表达式库(正则表达式详解、提取页面关键信息)

6、专业网络爬虫框架scrapy*(网络爬虫原理介绍、专业爬虫框架介绍)

IDE:集成开发环境,编写、调试、发布Python程序的工具。

常用的Python IDE工具有2大类:

一、文本工具类IDE

二、集成工具类IDE

IDLE:自带、默认、常用、入门级。包含交互式和文件式两种方式。

         使用:Python入门、功能简单直接、300+代码以内

sublime text:专为程序员开发的第三方专用编程工具、专业编程体验(专业程序员都用这个)、多种编程风格、工具非注册免费试用。

 Wing:公司维护,工具收费;调试功能丰富;版本控制,版本同步;适合多人共同开发

Visual Studio & PTVS:微软公司维护;win环境为主;调试功能丰富。

PyCharm:社区版免费;简单,集成度高;适合较复杂工程。

专门针对科学计算、数据分析的IDE

Canopy:公司维护,工具收费;支持近500个第三方库;适合科学计算领域应用开发。

Anaconda:开源免费;支持近800个第三方库。

Requests库入门

requests库安装:

1、打开“cmd”;2、输入:pip install requests;3、安装完成

requests库测试:  在IDLE操作

>>> import requests
>>> r = requests.get("http://www.baidu.com")
>>> r.status_code   # 查看r的状态码
200                 # 状态码为200表示爬取成功,不是200则访问失败
>>> r.encoding = "utf-8"
>>> r.text   # 下面内容表示成功爬取百度首页内容
'<!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'

requests库的7个主要方法

方法 说明
requests.request() 构造一个请求,是支撑一下各种方法的基础方法
requests.get() 获取HTML网页的主要方法,对应于HTTP的GET
requsets.head() 获取HTML网页头信息的方法,对应于HTTP的HEAD
requests.post() 向HTML网页提交POST请求的方法,对应于HTTP的POST
requests.put() 向HTML网页提交PUT请求的方法,对应于HTTP的PUT
requests.patch() 向HTML网页提交局部修改请求,对应于HTTP的PATCH
requests.delete() 向HTML网页提交删除请求,对应于HTTP的DELETE

requests.get()方法介绍

 r = requests.get(url)   # 获得一个网页

Response对象返回所有网页内容

requests.get(url, params=None, **kwargs)

url: 拟获取页面的url链接
params:url中的额外参数,字典或字节流格式,可选
**kwargs:12个控制访问的参数

Response对象的属性

属性 说明
r.status_code HTTP请求的返回状态,200表示链接成功,404表示失败(只要不是200就是失败)
r.text HTTP响应内容的字符串形式,即,url对应的页面内容
r.encoding 从HTTP header中猜测的响应内容编码方式
r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式)(更准确)推荐
r.content HTTP响应内容的二进制形式

 

r.encoding:根据HTTP中header中charset分析编码方式,如果header中不存在charset,则认为编码为ISO-8859-1

r.apparent_encoding:跟准确,根据HTTP内容分析可能的编码方式,

requests.get()方法获取网上资源的流程

1、用r.status_code方法检查返回的Response对象的状态。

 

爬取网页的通用代码框架

 网络爬取有风险,异常处理很重要

理解requests库的异常

异常 说明
requests.ConnectionError 网络连接错误异常,如DNS查询失败、防火墙拒绝连接等
requests.HTTPError HTTP错误异常
requests.URLReuired URL缺失异常
requests.TooManyRedirects 超过最大重定向次数,产生重定向异常
requests.ConnectTimeout 连接远程服务器超时异常(仅指与远程服务器连接过程超时)
requests.Timeout 请求URL超时,产生超时异常(发出URL请求到收到内容整个过程超时)
异常 说明
r.raise_for_status() 如果是200,则表示正确;如果不是200,则产生异常requests.HTTPError

爬取网页的通用代码框架

 1 import requests
 2 
 3 def getHTMLText(url):
 4     try:
 5         r = requests.get(url, timeout=30)
 6         r.raise_for_status()  # 如果状态不是200,引发HTTPError异常
 7         r.encoding = r.apparent_encoding
 8         return r.text
 9       except:
10         return "产生异常"
1 if __name__ == "__main__":
2     url = "http://www.baidu.com"
3     print(getHTTPText(url))

网络爬虫的盗亦有道--robots协议介绍

Requests库爬取实例

学习资料:中国大学MOOC-Python网络爬虫与信息提取

猜你喜欢

转载自www.cnblogs.com/chenpeng1024/p/9206387.html