【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 ...
随机推荐
- eclipse使用异常An error has occurred.see error log for more details eclipse
eclipse使用异常An error has occurred.see error log for more details eclipse 解决Eclipse,MyEclipse出现An erro ...
- 假设程序需要一个int类型的变量来保持你所有的音乐CD的数量
假设程序需要一个int类型的变量来保持你所有的音乐CD的数量.初始值为0为该变量编写一条声明语句 int numCDs = 0;
- Java 遍历List中删除的解决方法
- QR 编码原理(二)
编码就是把常见的数字.字符等转换成QR码的方法.说具体的编码之前,先说一下QR码的最大容量问题. 一.最大容量 QR码的最大容量取决于选择的版本.纠错级别和编码模式(Mode:数字.字符.多字节字符等 ...
- CF1102F Elongated Matrix
题目地址:CF1102F Elongated Matrix 没想到Div.3里还有这么好的题 其实就是求Hamilton路径 预处理 \(d\) 数组: \(d1_{i,j}\) 表示第 \(i,j\ ...
- 论文笔记:Rich feature hierarchies for accurate object detection and semantic segmentation
在上计算机视觉这门课的时候,老师曾经留过一个作业:识别一张 A4 纸上的手写数字.按照传统的做法,这种手写体或者验证码识别的项目,都是按照定位+分割+识别的套路.但凡上网搜一下,就能找到一堆识别的教程 ...
- Linux内核很吊之 module_init解析 (下)【转】
转自:https://blog.csdn.net/richard_liujh/article/details/46758073 版权声明:本文为博主原创文章,未经博主允许不得转载. https://b ...
- linux 用户空间获得纳秒级时间ns【转】
转自:https://www.cnblogs.com/kekukele/p/3662816.html 一.引言 我们在测试程序的性能的时候往往需要获得ns级的精确时间去衡量一个程序的性能,下面介绍下l ...
- sort和uniq去重操作【转】
去除重复行 sort file |uniq 查找非重复行 sort file |uniq -u 查找重复行 sort file |uniq -d 统计 sort file | uniq - ...
- RT-thread嵌入式操作系统相关的问题
面试中问到 RT-thread嵌入式操作系统相关的问题 RT-thread操作系统调度器的实现细节 RT-Thread中提供的线程调度器是基于优先级的全抢占式调度: 在系统中除了中断处理函数.调度器上 ...