Python学习笔记-httplib使用例子

本文介绍如何利用Python中的httplib库(Python 2)及http.client库(Python 3)进行网络数据的下载。通过读取本地文件中的ID列表,并针对每个ID构造HTTP请求,从指定服务器获取数据,然后将响应内容保存到本地文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景:

采用httplib进行网络数据的下载

代码:

#coding:utf-8
import httplib
file1 = open("ids.txt")
krcids = []
while 1:
    line = file1.readline()
    if not line:
        break
  line = line.strip('\n')#去掉行尾的换行
  str = line.split('\t')#对于一行存储多个字段信息的情况,需要进行字符串的分割,每一行存储两个字段信息,即按照列进行分割
  lislen = len(str)
  krcids.append(str[0])
  hashs.append(str[1])
    # do something

h1 = httplib.HTTPConnection('142.62.29.125', 8071, 10)

for tempkrc in krcids:
    print(tempkrc)
    url = "/gettext?id=" + tempkrc
    h1.request('GET', url)
    response = h1.getresponse()
<pre name="code" class="python">   <span style="display: none; width: 0px; height: 0px;" id="transmark"></span> print response.status
   print response.reason
   print response.read()
   print response.getheaders() #获取头信息
tempwrite = response.read() tempwrite = tempwrite.strip() #逐行操作,去除空白行 print(tempwrite) outfile = tempkrc + ".txt" output = open(outfile, 'w') output.write(tempwrite)h1.close()

注意:

不同版本的python,如2和3之间的差别还是比较大的。上述代码为python2环境下运行的。python3下的代码修改为:

import http.client
import urllib
import hashlib
import time
token = "ieK3keIO90^O39@bk2-kd"
clienttime1 = int(time.time())
acc_hash = token + str(clienttime1)
acc_hash = acc_hash.encode('utf-8')
key1 = hashlib.md5()
key1.update(acc_hash)
key1 = key1.hexdigest()


param = {
    'source': 13,
    'sn': 41600628,
    'clienttime': clienttime1,
    'key': key1
}
param = urllib.parse.urlencode(param)
#url1 = "www.baidu.com"
url1 = "data.media.kgidc.cn/index.php?m=audio"# % urllib.parse.urlencode(param)
print(url1)
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
h2 = http.client.HTTPConnection(url1)
h2.request("POST", "", param, headers)
#response = h2.getresponse()
# tempwrite = response.read()
# print(tempwrite)



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值