Python发送http请求解析返回json的实例

yipeiwu_com6年前Python基础

python发起http请求,并解析返回的json字符串的小demo,方便以后用到。

#! /usr/bin/env python
  # -*- coding:gbk -*-

  import os
  import sys
  import json
  import urllib
  import urllib2

  if __name__ == "__main__":
    query_file = sys.argv[1]
    query_index = 0
    with open(query_file, 'r') as fp:
      for line in fp:
        query = line.rstrip()
        query_index = query_index + 1
        query_gbk = query
        query = query.decode('gbk', 'ignore').encode('utf8', 'ignore')
        url = 'http://10.42.141.12:8089/adrender?query=%s&ad_num=3&srcid=101'\\
           '&ip=172.22.182.55&baiduid=61ABB404320C72436EB6B8352DFBB388:FG=1' % (query)
        req = urllib2.urlopen(url)
        page = req.read()
        ddict = json.loads(page)
        expid = ddict['expid']
        sid = ddict['sid']
        ad_num = ddict['response_adnum']
        for i in range(0, ad_num):
          output_html = '%s-%d.html' % (query_gbk, i)
          output = open(output_html, 'w')
          ad = ddict['response_ads'][i].encode('utf8', 'ignore')
          output.write('<html>\')
          output.write('<head>\  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\<head>\')
          output.write("%s" % (ad))
          output.write('\</html>\')
          output.close()

以上这篇Python发送http请求解析返回json的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python OpenCV之图片缩放的实现(cv2.resize)

Python OpenCV之图片缩放的实现(cv2.resize)

OpenCV函数原型: cv2.resize(InputArray src, OutputArray dst, Size, fx, fy, interpolation) 参数解释:...

Python动态声明变量赋值代码实例

这篇文章主要介绍了Python动态声明变量赋值代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 通过exec()、globals...

基于Django ORM、一对一、一对多、多对多的全面讲解

上篇博客也提到这些知识点,可能大家还是不太清楚,这篇博客为大家详细讲解ORM中的几个知识点 1.1首先我们先看一个小案例: #_*_coding:utf-8_*_ from djan...

解析python的局部变量和全局变量

局部变量 什么是局部变量 通俗定义:函数内部定义的变量就叫局部变量。 话不多说,代码如下: def test1(): a = 300 # 定义一个局部变量a,并初始化300 pr...

Python分析彩票记录并预测中奖号码过程详解

Python分析彩票记录并预测中奖号码过程详解

0 引言 上周被一则新闻震惊到了,《2454万元大奖无人认领!福彩史上第二大弃奖在广东中山产生 》,在2019年5月2日开奖的双色球中,广东中山一位彩民博中2454万元,兑奖时间截至2...