【问题标题】:Replace values within a URL in Python在 Python 中替换 URL 中的值
【发布时间】:2020-01-07 12:29:10
【问题描述】:

我有一个 URL,我想用字典中存在的值替换它的一些内容(中间),并将其保存在我的本地,文件名作为字典中的键名。我已经开始编码,但不知道如何继续。

URL = 'http://api.trkd.thomsonreuters.com/api/streetevents/documents/61145274-DB5A-454D-9A31-E6D24E77A7B1/Transcript/Pdf.ashx'

字典 n 具有以下键、值:

Nio Inc Earnings Call 8874A5B3-06BC-4863-9890-9F6775E1A219
China Finance Online Co Ltd Earnings Call D166208D-CE51-46BF-819A-DB34CBF85A97

将pdf保存到我的本地的代码

import requests

URL = 'http://api.trkd.thomsonreuters.com/api/streetevents/documents/61145274-DB5A-454D-9A31-E6D24E77A7B1/Transcript/Pdf.ashx'
r = requests.get(URL, stream=True, proxies=proxyDict)
with open('metadata.pdf', 'wb') as f:
 f.write(r.content)

我想遍历字典 'n' 并从中提取值部分并在 URL 中替换它。

例如 URL = 'http://api.trkd.thomsonreuters.com/api/streetevents/documents/61145274-DB5A-454D-9A31-E6D24E77A7B1/Transcript/Pdf.ashx' 应该更改为

网址 = 'http://api.trkd.thomsonreuters.com/api/streetevents/documents/8874A5B3-06BC-4863-9890-9F6775E1A219/Transcript/Pdf.ashx'

并下载名为“Nio Inc Earnings Call.pdf”的 pdf,然后再次将 URL 替换为字典中的下一个值,并使用其键名下载。

【问题讨论】:

    标签: python jupyter-notebook


    【解决方案1】:

    使用str.format 的简单迭代

    例如:

    import requests
    
    URL = 'http://api.trkd.thomsonreuters.com/api/streetevents/documents/{}/Transcript/Pdf.ashx'
    for k,v in n.items():
        r = requests.get(URL.format(v), stream=True, proxies=proxyDict)   #set value in URL
        with open('{}.pdf'.format(k), 'wb') as f:    #Set key as PDF name
            f.write(r.content)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多