使用python从mailchimp中的特定列表中检索订阅者的所有电子邮件地址

时间:2016-03-30 05:21:17

标签: python json dictionary md5 mailchimp

我试图从Mailchimp中的特定列表(具有唯一的listid)获取订阅者的所有电子邮件地址。

如果我打印正文,则输出为json格式,如下所示。

我正在尝试将json转换为字典。

将其转换为字典后,我想获取所有的email_address。

收到所有电子邮件地址后,我想使用md5对其进行加密。

但是我遇到错误'TypeError:expected string or buffer'。

我是python的新手,尝试解决它但不能。感谢您查看我的问题。

/* My python code */

params = { 
   'apikey': 'xyz',
   'listId':  'abc' }

config = MailChimpConfig() 
endpoint = "https://us5.api.mailchimp.com/3.0/lists/'listId'/members?   
apikey='apikey'&status=subscribed"

while True: 
   response = requests.get(endpoint, auth=('apikey', config.apikey),
                           params=params, verify=False)
   try:
     response.raise_for_status() 

     body = response.json
     dict = json.loads(body) 
     print(dict.members[0].email_address)
     break
   except requests.exceptions.HTTPError as err:
     print "Error: {} {}".format(str(response.status_code), err)
     print json.dumps(response.json(), indent=4)
     break
   except ValueError:
     print "Cannot decode json, got %s" % response.text
     break
   /* end of my python code */



/* If I print body, the output is in json format as below:*/

{
- members: [
  - {
       id: "",
        email_address: "x@hotmail.com",
        etc:""
    },
  - {
       id: "",
       email_address: "y@gmail.com",
       etc:""
    }

 /* end of json format */

1 个答案:

答案 0 :(得分:1)

这是不对的:

 body = response.json
 dict = json.loads(body) 

response.json不是JSON对象或str,它是一个函数。调用时,它返回一个Python对象,该对象表示响应的JSON中的数据。

试试这个:

# UNTESTED

# Interpret the JSON string:
data = response.json()

# Print one of the email addresses:
print(data['members'][0]['email_address'])

# Print all of the email addresses
addresses = [x['email_address'] for x in data['members']]
print(addresses)

获得地址列表后,您可以打印每个地址的MD5摘要:

# UNTESTED
for address in addresses:
    print(hashlib.md5(address.encode('utf-8')).hexdigest())

如果您希望打印一个代表所有地址的MD5:

# UNTESTED
md5 = hashlib.md5()
for address in sorted(addresses):
    md5.update(address.encode('utf-8'))
print(md5.hexdigest())