Python如何发送http请求解析返回json

发布时间:2021-07-23 13:54:15 作者:小新
来源:亿速云 阅读:735

这篇文章将为大家详细讲解有关Python如何发送http请求解析返回json,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

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”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. 使用Requests发送Http请求
  2. Python Ajax请求及返回 json

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

http python json

上一篇:如何使用coreseek并为其做分页

下一篇:PHP如何使用MySQL管理Session的回调函数

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》