【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 ...
随机推荐
- mui卡片视图的制作
<!doctype html> <html> <head> <meta charset="UTF-8"> <title> ...
- 【译】第四篇 SQL Server安全权限
本篇文章是SQL Server安全系列的第四篇,详细内容请参考原文. 权限授予主体访问对象,以执行某些操作.SQL Server有大量你可以授予给主体的权限,你甚至可以拒绝或回收权限.这听起来有点复杂 ...
- LOJ #2542「PKUWC2018」随机游走
$ Min$-$Max$容斥真好用 $ PKUWC$滚粗后这题一直在$ todolist$里 今天才补掉..还要更加努力啊.. LOJ #2542 题意:给一棵不超过$ 18$个节点的树,$ 5000 ...
- [Ynoi2016]这是我自己的发明 莫队
传送门:here 很棒的莫队题啊..... 题意: 有一棵$ n$个点的树,树上每个点有点权,有$ m$次询问: 操作1:给定两个点$ x,y$,求二元组$ (a,b)$的数量,要求$ a$在$ x$ ...
- 基于【字符】操作的IO接口:Writer、Reader
Reader public class BufferedReaderTest { public static void main(String[] args) throws IOException { ...
- 使用Retrofit时常用到的注解
- wx小程序-列表详细页点击跳转!
1.因为template 只是单纯的占位符,所以事件要写在外层view上面 2.通过自定义属性来判断 跳转的是那篇文章 自定义属性 (data-自定义名称 ) 3. 执行 onpostTap方 ...
- [Harbor]Docker登录Harbor仓库(HTTP方式)
Docker登录到Harbor仓库时,不管是使用http协议还是使用https协议,都需要修改一些配置. 这篇文章来介绍一下,在使用http协议时,需要进行什么哪些配置. 首先,确定自己的Harbor ...
- 基于FATFS的磁盘分布
1.前言 本文主要采用FAT32文件系统的磁盘各个部分是如何划分的 2. 磁盘分布总图 如包含两个分区的磁盘整体分布如下: 图 带有两个分区的磁盘分布 2.1 MBR 图 MBR的高层视图 主引导记 ...
- systemd实践: 依据情况自动重启服务【转】
1.最简单的自动重启范例 [Unit] Description=mytest [Service] Type=simple ExecStart=/root/mytest.sh Restart=alway ...