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设计】。

相关文章

Python2与Python3的区别实例分析

本文实例讲述了Python2与Python3的区别。分享给大家供大家参考,具体如下: python2与python3的区别 1、性能 2、编码格式utf-8 3、打印语句变成了打印函数...

python实现猜数字游戏

python实现猜数字游戏

说明: 本例改编自《Python编程快速上手》。例子很简单我就不多说了 直接上代码,给初学python练手用。 给你6次机会猜对一个预先生成好的1-20之间的整数。覆盖一下知识点:...

Python中使用PIPE操作Linux管道

Python中使用PIPE操作Linux管道

Linux中进程的通信方式有信号,管道,共享内存,消息队列socket等。其中管道是*nix系统进程间通信的最古老形式,所有*nix都提供这种通信方式。管道是一种半双工的通信机制,也就是...

Python列表推导式、字典推导式与集合推导式用法实例分析

本文实例讲述了Python列表推导式、字典推导式与集合推导式用法。分享给大家供大家参考,具体如下: 推导式comprehensions(又称解析式),是Python的一种独有特性。推导式...

python3中的md5加密实例

在python3的标准库中,已经移除了md5,而关于hash加密算法都放在hashlib这个标准库中,如SHA1、SHA224、SHA256、SHA384、SHA512和MD5算法等。...