【Python】python http 请求

python2.7 版

自定义设置代理、超时客户端

# -*- coding: utf-8 -*
# python2.7
import urllib2
import urllib
import json
import StringIO
import gzip
import sys
import socket
import logging
import random
import StringIO
import gzip

logging.basicConfig(
    level    = logging.DEBUG,
    format   = '%(asctime)s %(levelname)s %(process)d --- [%(threadName)s] %(filename)s %(funcName)s %(lineno)d : %(message)s',
    datefmt  = '%Y-%m-%d %H:%M:%S',
)


class JaguarClient(object):

    def __init__(self, proxy=None):
        handler = None
        if proxy is not None:
            handler = {"http":proxy}
        proxy_handler = urllib2.ProxyHandler(handler)
        self.__client = urllib2.build_opener(proxy_handler)


    def get(self, url, params=None):
        assert isinstance(url, str), "url must be str"
        if params is not None:
            assert isinstance(params, dict), "params must be dict"
            url = url + "?" + urllib.urlencode(params)
        response = None
        try:
            response = self.__client.open(url, timeout=10) # timeout 单位是秒
            if response.headers.get("content-encoding") == "gzip":
                gzipper = gzip.GzipFile(fileobj=StringIO.StringIO(response.read()))
                return gzipper.read()
            else:
                return response.read().decode("utf-8")
        except  IOError, err:
            if isinstance(err, socket.timeout):
                logging.error("Time Out | url: %s "%(url))
            else:
                logging.error("Requset | url: %s msg: %s"%(url, err))
            return None
        finally:
            if response is not None:
                response.close()

    def post_by_bodyIsJSON(self, url, header = {},params=None):
        assert isinstance(params, str), "params must be str"
        request = urllib2.Request(url, data=params, headers = header)
        response = self.__client.open(request, timeout=10)

        return response.code

def example():
    cli = JaguarClient()
    res_str = cli.get("http://www.sina.com")
    return res_str

def query_weater():
    city = ["杭州", "上海", "北京", "成都"]
    url = "http://wthrcdn.etouch.cn/weather_mini"
    cli = JaguarClient()
    res_str = cli.get(url, {"city":random.choice(city)})
    return res_str

if __name__ == "__main__":
    # res_str = example()
    res_str = query_weater()
    print res_str
# coding=UTF-8
# urllib2_get.py

import urllib2
import StringIO
import gzip

url = 'http://wthrcdn.etouch.cn/weather_mini?city=杭州'

response = urllib2.urlopen(url).read()

data = StringIO.StringIO(response)
gzipper = gzip.GzipFile(fileobj=data)
html = gzipper.read()

print
html

python3.6 版

import json
import requests
import sys

if len(sys.argv) < 2:
    print('Please city params !')
    sys.exit()

# 从命令行获取城市 索引1
city = sys.argv[1]

# 请求天气数据
url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + city
response = requests.get(url)
response.raise_for_status()  # 用来检查错误
weatherData = json.loads(response.text)  # 返回的是json数据
print(weatherData['data'])

转载于:https://www.cnblogs.com/jzsg/p/10926193.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值