1.traceback 模块, 打印异常信息
import traceback
try:
print(str(i) +"\t"+ resStr)
time.sleep(0.1)
except :
traceback.print_exc()
traceback.format_exc()
2.OS模块, 文件/目录方法
import os
sas=os.getcwd() #返回当前工作目录
print(sas)
3.Requests模块
#get类型
r = requests.get('https://github.com/timeline.json')
#post类型
r = requests.post("http://m.ctrip.com/post")
#put类型
r = requests.put("http://m.ctrip.com/put")
#delete类型
r = requests.delete("http://m.ctrip.com/delete")
#head类型
r = requests.head("http://m.ctrip.com/head")
#options类型
r = requests.options("http://m.ctrip.com/get")
print r.content
print r.text
# 发送无参数的get请求
baiDu_response = requests.get('http://www.baidu.com')
# 发送无参数的get请求 设置超时时间 timeout 单位秒
baiDu_response = requests.get('http://www.baidu.com', timeout=1)
# 查看发送请求的url地址
print('无参数的get请求地址为: ' + baiDu_response.url)
# 查看当前返回状态码
# 若状态码为200 等同于 baiDu_response.status_code == requests.codes.ok 返回为True
print('返回的状态码为: '+str(baiDu_response.status_code))
# 查看当前返回内容编码
print('返回内容编码格式为:' + baiDu_response.encoding)
# 查看当前返回内容 text返回的是字符串
print('Text返回的数据内容为:' + baiDu_response.text)
# 查看当前返回内容 content返回的是字节流
# print('Content返回的数据内容为:' + baiDu_response.content)
# 若返回内容为json格式 可用如下语句
# print('返回的Json数据为:' + baiDu_response.json())
# 获取服务器返回的原始数据 增加stream=True
# data = requests.get('https://api.github.com/events', stream=True)
# print(data.raw.read())
# 发送带参数(字典形式)的get请求
sendDictParams = {'key1': 'value1', 'key2': 'value2'}
baiDu_dictParams_response = requests.get('http://www.baidu.com', params=sendDictParams)
# 查看发送请求的url地址
print('普通参数的get请求地址为: ' + baiDu_dictParams_response.url)
# 发送list格式参数的get请求
sendListParams = {'key1': 'value1', 'key2': ['value2', 'value3']}
baiDu_listParams_response = requests.get('http://www.baidu.com', params=sendListParams)
# 查看发送请求的url地址
print('带list参数的get请求地址为: ' + baiDu_listParams_response.url)
4.json模块
- json.dumps 用于将 Python 对象编码成 JSON 字符串。
import json
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
json = json.dumps(data)
print json
[{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4}]
- json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。
import json
jsonData = '{"code":200,"result":[{"items":[],"recommendType":"als"},{"items":[{"category":"流行金曲","id":11680,"name":"因为遇见你","performer":["欢欢延陵人"],"score":106.0,"tag":"['音质优']"}],"recommendType":"cold_start"}]}
';
text = json.loads(jsonData)
print text
{
"code": 200,
"result": [{
"items": [],
"recommendType": "als"
}, {
"items": [{
"category": "流行金曲",
"id": 11680,
"name": "因为遇见你",
"performer": ["欢欢延陵人"],
"score": 106.0,
"tag": "['音质优']"
}],
"recommendType": "cold_start"
}]
}
示例
import json
import random
import requests
import time
import traceback
url = "http://" + host
with open('../data/log.txt', 'r', encoding='utf-8') as f, \
open('../result/tuijian.txt', 'w', encoding='utf-8') as frp:
i = 0;
for q in f.readlines():
globalId = str(random.randint(100000000, 200000000)) + str(int(time.time()))
data = {
"globalId": "11111",
"userId": q.replace('\n', ''),
"domain": "music",
"numReco": "1",
"category": ["音乐", "流行金曲"],
"tag": ["音质优"],
"recommendType": ["als", "item_based"]
}
i = i + 1;
try:
r = requests.post(url, json=data, timeout=1)
result = r.text.replace('\n', '').replace('\t', '')
print(str(i)+ "\t"+q.replace('\n', '') + "\t" + result)
frp.write(str(i) + "#" + q.replace('\n', '') + "#" + result + '\n')
result_dict = json.loads(result)
time.sleep(0.1)
except:
traceback.print_exc()
frp.flush()