【问题标题】:How do you read URLs from a .txt file to perform requests.get and save the responses to a file?您如何从 .t​​xt 文件中读取 URL 以执行 requests.get 并将响应保存到文件中?
【发布时间】:2020-08-06 01:31:22
【问题描述】:

我能够保存单个 URL 的响应,但我在 .txt 文件中有一个 URL 列表,并且想要打印所有响应。如何从 .t​​xt 文件中读取 URL 并将响应保存在 python 中?

这是我目前拥有的。谢谢!

import requests

data = requests.get('www.url.com')

with open('file.txt', 'wb') as f:
    f.write(data.text)

【问题讨论】:

  • 是否要将所有回复保存到同一个文件中?还是不同的文件?
  • 请同一个文件

标签: python database file get python-requests


【解决方案1】:

您首先要从文件“infile.txt”中读取 url,然后迭代发送请求并将数据写入输出文件“outfile.txt”。

with open('infile.txt', 'r') as f:
    urls = f.readlines()

datalist=[]
for url in urls:
    data = requests.get(url)
    datalist.append(data.text)

with open('outfile.txt', 'w') as f:
    for item in datalist:
        f.write("%s\n" % item)

【讨论】:

  • 非常感谢您花时间帮助我理解。祝你有美好的一天!
猜你喜欢
  • 1970-01-01
  • 2014-03-17
  • 2016-05-29
  • 1970-01-01
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 2021-03-13
  • 1970-01-01
相关资源
最近更新 更多