Spider_基础总结2_Requests异常
# 1: BeautifulSoup的基本使用:
import requests
from bs4 import BeautifulSoup
html=requests.get('https://www.pythonscraping.com/pages/page1.html')
bs=BeautifulSoup(html.text,'html.parser')
bs=BeautifulSoup(html.content,'html.parser')
print(bs.h1)
# 2:reponseobj.content和reponseobj.text区别:
# requests对象的get和post方法都会返回一个Response对象,这个对象里面存的是服务器返回的所有信息,包括响应头,响应状态码等。
# 其中返回的网页部分会存在.content和.text两个对象中。
# 两者区别在于,content中间存的是字节码,而text中存的是Beautifulsoup根据猜测的编码方式将content内容编码成字符串。
# 直接输出content,会发现前面存在b'这样的标志,这是字节字符串的标志,而text是,没有前面的b,对于纯ascii码,这两个可以说一模一样,对于其他的文字,
# 需要正确编码才能正常显示。大部分情况建议使用.text,因为显示的是汉字,但有时会显示乱码,这时需要用.content.decode('utf-8'),中文常用
# utf-8和GBK,GB2312等。这样可以手工选择文字编码方式。
# 所以简而言之: .text是现成的字符串,.content还要编码,但是.text不是所有时候显示都正常,这是就需要用.content进行手动编码。
# 3: beautifulsoup 的 4个解析器:
# html.parser lxml xml html5lib
# 区别和用法见 https://blog.csdn.net/huang1600301017/article/details/83474288
# 4:requests库的异常及处理:
from requests import exceptions
# exceptions.ConnectTimeout 连接远程服务超时,读取超时
# exceptions.ConnectionError 网络连接错误异常,比如DNS查询失败、拒绝连接,未知的服务器等
# exceptions.ProxyError 代理异常
# exceptions.ReadTimeout 读取超时
# exceptions.HTTPError HTTP错误异常
# exceptions.URLRequired URL缺失异常
# exceptions.TooManyRedirects 超过最大重定向次数,产生重定向异常
# exceptions.Timeout 请求 URL超时,产生超时异常
几个常见的异常解释:
1--超时异常:requests.exceptions.ConnectTimeout
1). 连接超时--服务器在指定时间内没有应答,抛出 requests.exceptions.ConnectTimeout
requests.get('http://github.com', timeout=0.001)
2). 连接、读取超时--若分别指定连接和读取的超时时间,服务器在指定时间没有应答,抛出 requests.exceptions.ConnectTimeout
- timeout=([连接超时时间], [读取超时时间])
- 连接:客户端连接服务器并并发送http请求服务器
- 读取:客户端等待服务器发送第一个字节之前的时间
requests.get('http://github.com', timeout=(6.05, 0.01))
3). 代理服务器没有响应 抛出 requests.exceptions.ConnectTimeout
requests.get('http://github.com', timeout=(6.05, 27.05), proxies={"http": "10.200.123.123:800"})
2--连接异常:requests.exceptions.ConnectionError
1).未知的服务器 抛出 requests.exceptions.ConnectionError
requests.get('http://github.comasf', timeout=(6.05, 27.05))
2).可能是断网导致 抛出 requests.exceptions.ConnectionError
requests.get('http://github.com', timeout=(6.05, 27.05))
3--代理服务器拒绝建立连接,端口拒绝连接或未开放,抛出 requests.exceptions.ProxyError
requests.get('http://github.com', timeout=(6.05, 27.05), proxies={"http": "192.168.10.1:800"})
4--代理读取超时
说明与代理建立连接成功,代理也发送请求到目标站点,但是代理读取目标站点资源超时
即使代理访问很快,如果代理服务器访问的目标站点超时,这个锅还是代理服务器背
假定代理可用,timeout就是向代理服务器的连接和读取过程的超时时间,不用关心代理服务器是否连接和读取成功
requests.get('http://github.com', timeout=(2, 0.01), proxies={"http": "192.168.10.1:800"})
# 以上异常的例子,请参见:https://blog.csdn.net/weixin_39198406/article/details/81482082
# 示例 1--Requests的使用:
import requests
html = requests.get('http://pythonscraping.com/pages/page1.html')
print(html) # <Response [200]>
# print(html.content) #字节串
print(html.text)
# <Response [200]>
# <html>
# <head>
# <title>A Useful Page</title>
# </head>
# <body>
# <h1>An Interesting Title</h1>
# <div>
# Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
# </div>
# </body>
# </html>
# 示例 2--BeautifulSoup的使用:
import requests
from bs4 import BeautifulSoup
html = requests.get('http://www.pythonscraping.com/pages/page1.html')
# bs = BeautifulSoup(html.content, 'html.parser') # 字节串
bs = BeautifulSoup(html.text, 'html.parser')
print(bs.h1)
# <h1>An Interesting Title</h1>
# 示例 3--异常处理:
import requests
from requests import exceptions
try:
# html = requests.get("https://pythonscrapingthisurldoesnotexist.com")
html = requests.get('http://www.pythonscraping.com/pages/page1.html',timeout=0.001)
except exceptions.ConnectionError as e:
print("The server returned an HTTP error")
except exceptions.ConnectTimeout as e:
print("The server could not be found!")
else:
print(html.text)
# The server returned an HTTP error
import requests
from requests import exceptions
from bs4 import BeautifulSoup
def getTitle(url,timeout):
try:
html = requests.get(url,timeout=timeout)
except exceptions.ConnectionError as e:
return None
try:
bsObj = BeautifulSoup(html.text, "lxml")
title = bsObj.body.h1
except exceptions.ConnectTimeout as e:
return None
return title
# title = getTitle("http://www.pythonscraping.com/pages/page1.html",0.001)
title = getTitle("https://pythonscrapingthisurldoesnotexist.com",(5,0.01))
if title == None:
print("Title could not be found")
else:
print(title)
# Title could not be found
import requests
from requests import exceptions
from bs4 import BeautifulSoup
def getTitle(url):
try:
html = requests.get(url)
print(type(html)) # <class 'requests.models.Response'>
except exceptions.HttpError as e:
return None
bs = BeautifulSoup(html.text, "lxml")
title = bs.body.h1
return title
title = getTitle("http://www.pythonscraping.com/pages/page1000.html")
print(type(title)) # <class 'bs4.element.Tag'> bs4构建的对象,不是requests返回的对象
if title == None:
print("Title could not be found")
else:
print(title)
# <class 'requests.models.Response'>
# <class 'bs4.element.Tag'>
# <h1 class="title" id="page-title">
# Page not found </h1>
Spider_基础总结2_Requests异常的更多相关文章
- Java基础学习补充 -- 异常处理和log4j日志
Java中的异常处理 异常是程序中的一些错误,但并不是所有的错误都是异常,并且错误有时候是可以避免的. Java中所有异常的基类Throwable:Throwable又分为Error类和Excepti ...
- javase基础笔记4——异常/单例和类集框架
继承 extends final关键 多态 是在继承的基础上 接口 interface 异常 exception 包的访问可控制权限 private default protect public 异常 ...
- Python基础之模块+异常
一.模块相关概念 1.定义:包含一系列数据.函数.类的文件,通常以.py结尾. 2.作用:让一些相关的数据,函数,类有逻辑的组织在一起,使逻辑结构更加清晰.有利于多人合作开发. 3.模块导入方式(三种 ...
- Python基础+模块、异常
date:2018414+2018415 day1+2 一.python基础 #coding=utf-8 #注释 #算数运算 +(加) -(减) *(乘) /(除) //(取整) %(取余) ...
- 【Java基础】Java异常的一些总结
什么是异常 异常是指程序运行可能出现的不能正常继续的情况,也可以理解为程序出现了不在预期范围内的一些情况,都可以称之为异常. 异常的分类 所有的异常类是从java.lang.Exception类继承的 ...
- Java基础语法<十一> 异常 断言 日志 调试
1 处理错误 1.1 异常分类 Error类层次描述了Java运行时系统的内部错误和资源耗尽错误. 设计Java程序时,主要关注Exception层次结构. 由程序错误导致的异常属于RuntimeEx ...
- jsp基础语言-jsp异常
JSP异常 jsp页面执行时会出现两种异常,实际是javax.servlet.jsp包中的两类异常JsError和JspException. 1.JsError 在jsp文件转换成servlet文件时 ...
- Java基础教程(22)--异常
一.什么是异常 异常就是发生在程序的执行期间,破坏程序指令的正常流程的事件.当方法中出现错误时,该方法会创建一个对象并将其交给运行时系统.该对象称为异常对象,它包含有关错误的信息,包括错误的类型和 ...
- python基础学习1 -异常捕获
#!/usr/bin/env python # -*- coding:utf-8 -*- #-------try-except try: file_name = input("请输入需要打开 ...
随机推荐
- js 正则表达式 判断val是不是整数
function isIntNum(val){ var regPos = / ^\d+$/; // 非负整数 // var regNeg = /^\-[1-9][0-9]*$/; // 负整数 if( ...
- RHSA-2018:3665-重要: NetworkManager 安全更新
[root@localhost ~]# cat /etc/redhat-release CentOS Linux release 7.2.1511 (Core) 修复命令: 使用root账号登陆She ...
- linux启动过程中建立临时页表
intel的x86这种架构为了兼容以前同系列的架构有一些很繁琐无用的东西.比如分段和分页两种机制都可以实现隔离进程的内存空间,在x86上两种机制都有,用起来比较繁琐.所以linux内核在启动的时候通过 ...
- Mac快捷键整理(随时更新)
一.文字编辑 快捷键 含义 解释 control + A 到行首 A没找到对应单词,暂时认为A是字母表的开始 control + E 到行尾 E是end的缩写
- Linux操作系统的基本介绍
01 操作系统的概述介绍 操作系统(Operating System,简称OS)是管理计算机硬件与软件资源的计算机程序.操作系统需要处理如管理与配置内存.决定系统资源供需的优先次序.控制输入设备与输出 ...
- Java改写重构第2版第一个示例
写在前面 <重构:改善既有代码的设计>是一本经典的软件工程必读书籍.作者马丁·福勒强调重构技术是以微小的步伐修改程序. 但是,从国内的情况来而论,"重构"的概念表里分离 ...
- Seaborn系列 | 散点图scatterplot()
散点图 解读 可以通过调整颜色.大小和样式等参数来显示数据之间的关系. 函数原型 seaborn.scatterplot(x=None, y=None, hue=None, style=None, s ...
- Linux运维学习第五周记
休惊岁岁年年貌 且对朝朝暮暮人 细雨晴时一百六 画船鼍鼓莫违民 雨生百谷,春雨贵如油 第五周学记 这周主要学习了九三级磁盘.存储相关知识和Linux文件系统以及计算机网络的内容 磁盘和文件系统 磁盘结 ...
- Anderson《空气动力学基础》5th读书笔记 第0记——白金汉PI定理
目录 量纲分析:白金汉PI定理 相似参数 量纲分析:白金汉PI定理 在空气动力学中,飞机的空气动力主要由自由来流的密度ρ∞,自由来流数V∞,翼弦长度c,自由来流的粘性系数μ∞以及音速a∞,所以假设我们 ...
- 虚拟环境与local_settings
虚拟环境(virtualenv) 对于同时管理多个不同的项目时,使用虚拟环境是必须的. 虚拟环境就是用来为一个项目新建一个全新的纯净的python运行环境,该环境与系统的python环境相互隔离,且虚 ...