# 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异常的更多相关文章

  1. Java基础学习补充 -- 异常处理和log4j日志

    Java中的异常处理 异常是程序中的一些错误,但并不是所有的错误都是异常,并且错误有时候是可以避免的. Java中所有异常的基类Throwable:Throwable又分为Error类和Excepti ...

  2. javase基础笔记4——异常/单例和类集框架

    继承 extends final关键 多态 是在继承的基础上 接口 interface 异常 exception 包的访问可控制权限 private default protect public 异常 ...

  3. Python基础之模块+异常

    一.模块相关概念 1.定义:包含一系列数据.函数.类的文件,通常以.py结尾. 2.作用:让一些相关的数据,函数,类有逻辑的组织在一起,使逻辑结构更加清晰.有利于多人合作开发. 3.模块导入方式(三种 ...

  4. Python基础+模块、异常

    date:2018414+2018415 day1+2 一.python基础 #coding=utf-8 #注释 #算数运算 +(加)  -(减)  *(乘)  /(除)  //(取整)  %(取余) ...

  5. 【Java基础】Java异常的一些总结

    什么是异常 异常是指程序运行可能出现的不能正常继续的情况,也可以理解为程序出现了不在预期范围内的一些情况,都可以称之为异常. 异常的分类 所有的异常类是从java.lang.Exception类继承的 ...

  6. Java基础语法<十一> 异常 断言 日志 调试

    1 处理错误 1.1 异常分类 Error类层次描述了Java运行时系统的内部错误和资源耗尽错误. 设计Java程序时,主要关注Exception层次结构. 由程序错误导致的异常属于RuntimeEx ...

  7. jsp基础语言-jsp异常

    JSP异常 jsp页面执行时会出现两种异常,实际是javax.servlet.jsp包中的两类异常JsError和JspException. 1.JsError 在jsp文件转换成servlet文件时 ...

  8. Java基础教程(22)--异常

    一.什么是异常   异常就是发生在程序的执行期间,破坏程序指令的正常流程的事件.当方法中出现错误时,该方法会创建一个对象并将其交给运行时系统.该对象称为异常对象,它包含有关错误的信息,包括错误的类型和 ...

  9. python基础学习1 -异常捕获

    #!/usr/bin/env python # -*- coding:utf-8 -*- #-------try-except try: file_name = input("请输入需要打开 ...

随机推荐

  1. CentOS7 执行 service iptables save 报错 The service command supports only basic LSB actions xxxxxx

    现象描述 在 CentOS 7.6.1810 下执行 service iptables save 命令,出现如下错误: [root@test ~]# service iptables save The ...

  2. Fabric1.4.4 基础环境搭建

    简单记录一下fabric版本1.4.4的环境搭建部署,运行环境为CentOs7.8,如有错误欢迎批评指正. 1.Docker 和 Docker Compose 1. docker的安装部署 docke ...

  3. java流程控制学习

    Java流程控制 计算的步骤就是算法. 1.用户交互Scanner next()不能得到带有空格的字符串.[它是以空格为结束符]nextline()可以,[它是以回车为结束符] 2.顺序结构 从上到下 ...

  4. 多测师讲解selenium_运行报告相出错归纳_高级讲师肖sir

    <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'> EETraceback (most recent c ...

  5. Spring Boot 系列:日志动态配置详解

    世界上最快的捷径,就是脚踏实地,本文已收录架构技术专栏关注这个喜欢分享的地方. 开源项目: 分布式监控(Gitee GVP最有价值开源项目 ):https://gitee.com/sanjianket ...

  6. fastdfs之同一台storage server下包含多个store path

    一,查看本地centos的版本 [root@localhost lib]# cat /etc/redhat-release CentOS Linux release 8.1.1911 (Core) 说 ...

  7. linux(centos8):sed命令的应用例子

    一,sed命令的用途 sed是Linux下一款功能强大的非交互流式文本编辑器, 可以对文本文件进行增.删.改.查等操作, 支持按行.按字段.按正则匹配文本内容. 说明:刘宏缔的架构森林是一个专注架构的 ...

  8. selenium--数据填充

    from time import sleep from selenium import webdriver br = webdriver.Chrome() url = "https://ww ...

  9. Codeforces Round #676 (Div. 2) A - D个人题解(E题待补)

    1421A. XORwice 题目链接:Click Here // Author : RioTian // Time : 20/10/18 #include <bits/stdc++.h> ...

  10. HTTP协议和APACHE

    HTTP服务 超文本传输协议. 互联网上应用最广的一种服务. 是一种应用层协议. Internet 互联网表示把各个网连起来 ARPAnet军网 TCP/IP协议 开放的协议 互联互通 Interne ...