我有以下Python 2.7脚本:
import urllib as ul
tracking_id = "abcde=="
encodedtrackingid = ul.quote(tracking_id)
mcid = "123456"
URL = "https://example.com/id?abcd&d_mid="+mcid+"&=124"+encodedtrackingid+"%011"
print URL
from mechanize import Browser
br = Browser()
br.set_handle_robots(False)
response = br.open(URL)
print response.read()
import requests
url = "https://example.net/rest/v1/mbox/4513452615415"
querystring = {"client":"example"}
payload = "{\r\n \"mbox\" : \"example\",\r\n\"CloudVisitorId\":\""+mcid+"\",\r\n \"thirdPartyId\": \""+tracking_id+"\",\r\n \"contentAsJson\": \"true\",\r\n \"mboxParameters\": \r\n { \r\n \"mboxMCGLH\": \"6\" \r\n }\r\n}\r\n"
headers = {
'content-type': "application/json",
'cache-control': "no-cache",
'postman-token': "289879f645d-1543-e6df-87fb-1cef88f55110c5"
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print(response.text)
我想做的是以下内容:
a)通过从CSV文件更新tracking_id和mcid变量来重复此脚本。
CSV文件没有标题,并且包含以下列:
列:A - tracking_id 专栏:B - mcid
我需要脚本读取CSV文件运行第1行的脚本,然后对第2行,第3行,第4行等重复相同的过程。每次脚本运行tracking_id和mcid变量更新,以及输出响应变量存储在CSV文件中。
最终结果将是具有以下内容的CSV文件: A列 - tracking_id B栏 - mcid C栏 - 回应
非常感谢任何帮助。
由于
答案 0 :(得分:1)
首先,我将初始脚本包装在一个函数(下面的代码中为myfunction
)中,将tracking_id
和mcid
作为参数并返回您希望的值检索。
import csv
# Loading csv
with open("mycsv.csv", 'r') as csv_file:
reader = csv.reader(csv_file)
# Reading row by row
for row in reader:
tracking_id = row[0]
mcid = row[1]
# Getting result
result = myfunction(tracking_id, mcid)
# Opening csv result file in append mode
with open("mycsv_result.csv", "a+") as csv_save:
writer = csv.writer(csv_save)
writer.writerow([tracking_id, mcid, result])
csv_save.close()
然后这个脚本就可以了。
编辑:
这是缺少的功能。我还建议您read this以了解如何创建基本功能。
def myfunction(tracking_id, mcid):
import urllib as ul
encodedtrackingid = ul.quote(tracking_id)
URL = "https://example.com/id?abcd&d_mid=" + mcid + "&=124" + encodedtrackingid + "%011"
print
URL
from mechanize import Browser
br = Browser()
br.set_handle_robots(False)
response = br.open(URL)
print
response.read()
import requests
url = "https://example.net/rest/v1/mbox/4513452615415"
querystring = {"client": "example"}
payload = "{\r\n \"mbox\" : \"example\",\r\n\"CloudVisitorId\":\"" + mcid + "\",\r\n \"thirdPartyId\": \"" + tracking_id + "\",\r\n \"contentAsJson\": \"true\",\r\n \"mboxParameters\": \r\n { \r\n \"mboxMCGLH\": \"6\" \r\n }\r\n}\r\n"
headers = {
'content-type': "application/json",
'cache-control': "no-cache",
'postman-token': "289879f645d-1543-e6df-87fb-1cef88f55110c5"
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
return response
答案 1 :(得分:0)
def dependsVersion = '1.2'
dependencies {
compile "groupId:artifactId:${dependsVersion}"
}
以下是一段时间前编写的示例代码,用于解析以空格分隔的CSV文件,您可以根据自己的要求进行修改。我希望这会有用。