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("请输入需要打开 ...
随机推荐
- 添加Google网络地图功能
在MeteoInfo中添加了Google网络地图功能.打开MeteoInfo软件,选中图层管理区的一个Map Frame(New Map Frame),点击鼠标右键,在弹出菜单中点击Add Web L ...
- 自定义常用input表单元素一:纯css 实现自定义checkbox复选框
最下面那个是之前写的 今天在做项目的时候发现,之前写的貌似还是有点多,起码增加的span标签可以去掉,这样保持和原生相同的结构最好的,仅仅是样式上的变化.今天把项目中的这个给更新上来.下面就直接还是 ...
- docker启动服务---------------rabbitmq
1.进入docker hub镜像仓库地址:https://hub.docker.com/ 2.搜索rabbitMq,进入官方的镜像,可以看到以下几种类型的镜像:我们选择带有"mangemen ...
- gorm学习地址
1 gorm curd指南 2 gorm入门指南
- php查看进程
index.php <?php /** * Created by PhpStorm. * User: mac * Date: 2020/4/23 * Time: 21:57 */ echo ...
- Jira 8.5.1 安装教程
Jira安装教程 一.CentOS设置 1. 更换阿里源 curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/rep ...
- History和Screen的对象属性
History 对象是 window 对象的一部分,可通过 window.history 属性对其进行访问. 属性 说明 length 返回历史列表中的网址数 History 对象方法 方法 说明 b ...
- <article>
今天介绍的是html中<article>标签的用法,如果有兴趣的朋友可以看一下! <article> 标签规定独立的自包含内容. 一篇文章应有其自身的意义,应该有可能独立于站点 ...
- C# 获取两点(经纬度表示)间的距离
#region 获取两点(经纬度表示)间的距离 /// <summary> /// 获取两点(经纬度表示)间的距离 /// </summary> /// <param n ...
- 结对项目的PS表格
PSP2.1 Personal Software Process Stages 预估耗时(分钟) 实际耗时(分钟) Planning 计划 60 80 Estimate 估计这个任务需要多少时间 10 ...