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 Dataframe 指定多列去重、求差集的方法

1)去重 指定多列去重,这是在dataframe没有独一无二的字段作为PK(主键)时,需要指定多个字段一起作为该行的PK,在这种情况下对整体数据进行去重。 Attention:主要用到了...

Python中shutil模块的学习笔记教程

介绍 shutil 名字来源于 shell utilities,有学习或了解过Linux的人应该都对 shell 不陌生,可以借此来记忆模块的名称。该模块拥有许多文件(夹)操作的功能,包...

python中使用while循环的实例

python中使用while循环的实例

python中for循环用于针对集合中的每个元素的一个代码块,而while循环能实现满足条件下的不断运行。 使用while循环时,由于while只要满足条件就会执行代码,故必须指定结束条...

Python反转序列的方法实例分析

本文实例讲述了Python反转序列的方法。分享给大家供大家参考,具体如下: 序列是python中最基本的数据结构,序列中每个元素都有一个跟位置相关的序号,也称为索引。对于一个有N个元素的...

pip install python 快速安装模块的教程图解

pip install python 快速安装模块的教程图解

之前python安装模块要在网络上下载,从python2.7.9之后,以及python3,python就自带pip 这个命令,能够快速的安装模块 1, 首先打开python的主文件夹...