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("请输入需要打开 ...
随机推荐
- S3C6410触摸屏驱动分析
一. device的注册1.0 两个注册//在smdk6410_machine_init中既注册了touchscreen的私有信息也注册了ts资源 1 在arch/arm/mach-s3c64xx/m ...
- 【Jenkins】active choices reactive parameter & Groovy Postbuild插件使用!
注:以上俩插件安装下载直接去jenkins官网或者百度下载即可 一.active choices reactive parameter 插件的使用 1.被关联的参数不做改动 2.添加active ch ...
- C#使用RabbitMq队列(Sample,Work,Fanout,Direct等模式的简单使用)
1:RabbitMQ是个啥?(专业术语参考自网络) RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件(亦称面向消息的中间件). RabbitMQ服务器是用Erlang语言编写的, ...
- JAVA Schedule的Cron表达式
spring中用到的定时任务,一般用到的有Timer()和Schedule Cron表达式一般是程序的定时任务中所要起的..我们用的springboot中的@Schedule中,启动类中添加enabl ...
- C# 微支付 JSAPI支付方式 V3.3.6版本
<script type="text/javascript">//结算 (订单号) function PayClearing(num) { $.ajax({ type: ...
- Sentinel流控规则
流控规则 注:Sentinel的监控页面一开始是没有东西,需要对监控的服务发起请求后才会出现 资源名:唯一名称,默认请求路径 针对来源:Sentinel可以针对调用者进行限流,填写微服务名,指定对哪个 ...
- ASP.NET Core托管运行Quartz.NET作业调度详解
Quartz.NET这么NB的作业调度系统,不会还行? 今天介绍一下Quartz.NET的托管运行,官网传送门. 一.前言 Quartz.NET,按官网上的说法,是一款功能齐全的任务调度系统,从小 ...
- 简述BIO到NIO的过程
BIO到NIO的图示
- 实战四:Gateway网关作全局路由转发
Gateway网关的作用主要是两个:路由转发,请求过滤.此篇讲的是路由转发,下篇介绍请求过滤. 一,创建网关module,添加依赖 1,new -> module -> maven 或直接 ...
- Kubernetes K8S之调度器kube-scheduler详解
Kubernetes K8S之调度器kube-scheduler概述与详解 kube-scheduler调度概述 在 Kubernetes 中,调度是指将 Pod 放置到合适的 Node 节点上,然后 ...