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传值与传址

1. 传值与传址的区别 传值就是传入一个参数的值,传址就是传入一个参数的地址,也就是内存的地址(相当于指针)。他们的区别是如果函数里面对传入的参数重新赋值,函数外的全局变量是否相应改变:...

Python操作MySQL数据库的三种方法总结

Python操作MySQL数据库的三种方法总结

1. MySQLdb 的使用 (1) 什么是MySQLdb? MySQLdb 是用于 Python 连接 MySQL 数据库的接口,它实现了 Python 数据库 API 规范 V2.0...

浅谈pandas中Dataframe的查询方法([], loc, iloc, at, iat, ix)

pandas为我们提供了多种切片方法,而要是不太了解这些方法,就会经常容易混淆。下面举例对这些切片方法进行说明。 数据介绍 先随机生成一组数据: In [5]: rnd_1 = [r...

解决django-xadmin列表页filter关联对象搜索问题

环境:xadmin-for-python3 python3.5.2 django1.9.12 问题描述:Product ProductSku两个实体,ProductSku FK外键关联P...

python进程的状态、创建及使用方法详解

本文实例讲述了python进程的状态、创建及使用方法。分享给大家供大家参考,具体如下: 进程以及状态 1. 进程 程序:例如xxx.py这是程序,是一个静态的 进程:一个程序运行起来后,...