【python】获取http响应
一个相对完整的http请求,输入ip和端口,输出响应码,响应头,响应体,是否超时,以及出错时的错误信息
处理包括:
1.协议处理,如果是443用https,其他用http
2.HTTPError处理,HTTPError一般是401,403,404之类的错误,虽然报错,但是也有响应头。注意获取错误信息时要用str(e),其他的比如repr(e)得到的不是字符串,e.read()是响应体,不是错误原因
3.URLError处理,一般是Connection refused之类的错误。注意获取错误信息时要用str(e.reason)
4.响应体gzip解压
5.响应体编码转换
# coding=utf8 import urllib2
import chardet
import traceback
import StringIO
import re
import gzip def plugin_homepage(data, timeout):
ip = data["ip"]
port = data["port"]
if port == 443:
url = "https://%s:%s/" % (ip, port)
else:
url = "http://%s:%s/" % (ip, port)
is_timeout, error_reason, code, header, body, title = get_html(url, timeout)
res = {"ip": ip,
"port": port,
"rsp_header": header,
"rsp_body": body,
"code": code,
"title": title,
"is_timeout": is_timeout,
"error_reason": error_reason}
return res def get_html(url, timeout):
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent': user_agent}
is_timeout = False
error_reason = None
code = None
header = None
body = None
title = None
try:
request = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(request, timeout=timeout)
code = response.getcode()
body = response.read()
header = str(response.headers)
except urllib2.HTTPError, e: # 处理http错误
# print "str(e):%s\nrepr(e):%s\ne:%s\ne.read():%s\n" % (str(e), repr(e), e, e.read())
error_reason = str(e)
body = e.read()
header = e.headers
except urllib2.URLError, e:
print traceback.print_exc()
error_reason = str(e.reason)
if error_reason == "timed out": # 判断是否超时
is_timeout = True
return is_timeout, error_reason, code, header, body, title
except Exception, e:
print traceback.print_exc()
error_reason = str(e)
return is_timeout, error_reason, code, header, body, title
if not header:
return is_timeout, error_reason, code, header, body, title
# 解压gzip
if 'Content-Encoding' in header and 'gzip' in header['Content-Encoding']:
html_data = StringIO.StringIO(body)
gz = gzip.GzipFile(fileobj=html_data)
body = gz.read()
# 编码转换
try:
html_encode = get_encode(header, body).strip()
if html_encode and len(html_encode) < 12:
body = body.decode(html_encode).encode('utf-8')
except:
pass
# 获取title
try:
title = re.search(r'<title>(.*?)</title>', body, flags=re.I | re.M)
if title:
title = title.group(1)
except:
pass
return is_timeout, error_reason, code, str(header), body, title # 获取html编码
def get_encode(header, body):
try:
m = re.search(r'<meta.*?charset=(.*?)"(>| |/)', body, flags=re.I)
if m:
return m.group(1).replace('"', '')
except:
pass
try:
if 'Content-Type' in header:
Content_Type = header['Content-Type']
m = re.search(r'.*?charset=(.*?)(;|$)', Content_Type, flags=re.I)
if m:
return m.group(1)
except:
pass
chardit1 = chardet.detect(body)
encode_method = chardit1['encoding']
return encode_method if __name__ == "__main__":
data = {"ip": "127.0.0.1", "port": 80}
res = plugin_homepage(data, 3)
print res
【python】获取http响应的更多相关文章
- python获取url响应
前言 requests发请求时,接口的响应时间,也是我们需要关注的一个点,如果响应时间太长,也是不合理的.如果服务端没及时响应,也不能一直等着,可以设置一个timeout超时的时间 关于request ...
- Python+requests 发送简单请求--》获取响应状态--》获取请求响应数据
Python+requests 发送简单请求-->获取响应状态-->获取请求响应数据 1.环境:安装了Python和vscode编译器(Python自带的编译器也ok).fiddler抓包 ...
- python获取响应某个字段值的三种方法
近期将要对两个接口进行测试,第一个接口的响应值是第二个接口的查询条件.为了一劳永逸,打算写个自动化测试框架.因为请求和响应都是xml格式的,遇到的问题就是怎么获取xml响应的某一个值.尝试了很多博客的 ...
- python获取网络时间和本地时间
今天我们来看一下如何用python获取网络时间和本地时间,直接上代码吧,代码中都有注释. python获取网络时间 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...
- urllib的实现---timeout,获取http响应码,重定向,proxy的设置
1.Timeout设置超时 只能修改Socket设置全局Timeout #! /usr/bin/env python3 import socket import urllib.request # ti ...
- Java学习-055-Jsoup爬虫通过设置获取响应数据大小的最大值,解决因默认获取 1MB 响应数据导致的无法获取全部的响应数据内容问题
在日常工作中,通常会遇到获取各种网络数据使用的情况,Java中可使用Jsoup(Python中可使用 BeatifulSoup)进行数据的获取及处理. 今天有朋友问,在使用 Jsoup 进行请求数据时 ...
- python+requests 请求响应文本出错返回“登录超时”
Python+requests请求响应:"msg":"登录过时" 1.出错原代码: import requests import json#页面按条件搜索返回相 ...
- 使用shell/python获取hostname/fqdn释疑
一直以来被Linux的hostname和fqdn(Fully Qualified Domain Name)困惑了好久,今天专门抽时间把它们的使用细节弄清了. 一.设置hostname/fqdn 在Li ...
- python 获取日期
转载 原文:python 获取日期 作者:m4774411wang python 获取日期我们需要用到time模块,比如time.strftime方法 time.strftime('%Y-%m-% ...
- python获取字母在字母表对应位置的几种方法及性能对比较
python获取字母在字母表对应位置的几种方法及性能对比较 某些情况下要求我们查出字母在字母表中的顺序,A = 1,B = 2 , C = 3, 以此类推,比如这道题目 https://project ...
随机推荐
- Linux和进程内存模型
一.Linux和进程内存模型 jvm是一个进程的身份运行在linux系统上,了解linux和进程的内存关系,是理解jvm和Linux内存关系的基础. 硬件.系统.进程三个层面的内存之间的概要关系 1. ...
- bae64编码
data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAEAAAAkCAYAAABIdFAMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJb ...
- 常用linux命令总结
Linux 版本 centos 1.查看Linux版本 uname -a 2.查看 ip 地址 ip addr 3.查看端口应用程序 netstat -lanp 如果输入上述命令,显示“-bash: ...
- pythonの连接MySQL数据库
1.要确保开发环境中安装了pymsql,如果没有安装那么在控制台输入: pip3 install pymysql 安装完成后,打开编辑器: #!/usr/bin/env python import p ...
- Python全栈(第一部分)day3
昨日内容回顾 格式化输出 %s %d %% 编码 ascii: 只能显示英文,特殊字符,数字 万国码unicode: 最开始16位,中文不够,用32位,占用4个字节 升级: utf-8 utf-16 ...
- 707. Design Linked List
1. 原始题目 Design your implementation of the linked list. You can choose to use the singly linked list ...
- boost.lexical_cast 学习
1,字符串 到 数值类型的转换 2,数值 到 字符串的转换 3,异常处理情况 4,boost::lexical_cast 的原型: template<typename Target, typen ...
- 题解-CodeForces835F Roads in the Kingdom
Problem CodeForces-835F 题意:求基环树删去环上任意一边后直径最小值,直径定义为所有点对最近距离的最大值 Solution 首先明确删去环上一点是不会影响树内直径的,所以应当先把 ...
- 题解-TIOJ1905 最理想的身高差
Problem 题目原型 题目大意:求区间最小差值 序列长度\(1e5\),询问\(2e5\) Solution 总体思路就是找出所有可能作为答案的点对,用资料结构_(:зゝ∠)_维护,然后询问 至于 ...
- 通过python操作smtplib模块发送邮件
# gconf.py SMTP_SERVER_HOST='smtp.exmail.qq.com' SMTP_SERVER_PORT=25 SMTP_USER='jack@qq.com' # 邮箱客户端 ...