gpt4 book ai didi

python - 使用 urllib3 和 python 2.7 从 url 下载 .txt 文件?

转载 作者:行者123 更新时间:2023-12-01 00:21:06 24 4
gpt4 key购买 nike

我使用的是 Python 2.7,并且有 urllib3。我正在尝试下载此链接中的每个 .txt 文件:http://web.mta.info/developers/turnstile.html

这是我的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
import requests
import urllib3, shutil


http = urllib3.PoolManager()

MTA_url = requests.get("http://web.mta.info/developers/turnstile.html").text
MTA_soup = BeautifulSoup(MTA_url)
#Find each link to be downloaded
MTA_soup.findAll('a')
#Let's test it with the 36th link
one_a_tag = MTA_soup.findAll("a")[36]
MTA_link = one_a_tag["href"]

download_url = 'http://web.mta.info/developers/'+ MTA_link
print download_url #valid url, will take you to download

这就是我被困住的地方。我似乎不知道如何在 download_url 下载 .txt 文件,更不用说迭代列表了。我试过这个:

open('/Users/me/Documents/test_output_download.csv', 'wb').write(download_url.content)

但这给了我错误:

AttributeError: 'unicode' object has no attribute 'content'

进一步阅读后,我也尝试过:

out_file = '/Users/me/Documents/test_output_download.csv'
http.request('GET', download_url, preload_content=False) as res, open(out_file, 'wb') as out_file:
shutil.copyfileobj(res, out_file)

但是我克服了这个语法错误:

    http.request('GET', download_url, preload_content=False) as res, open(out_file, 'wb') as out_file:
^
SyntaxError: invalid syntax

如何使用 urllib3 下载位于 download_url 的 .txt 文件并将其保存到本地驱动器?预先感谢您。

最佳答案

“as”关键字用于导入。我测试了完整的代码段,并在此处进行了一些小更改后能够下载。

尝试改变这一点以将对象声明为变量,如下所示:

res = http.request('GET', download_url, preload_content=False)

out_file = open(out_file, 'wb')
shutil.copyfileobj(res, out_file)

关于python - 使用 urllib3 和 python 2.7 从 url 下载 .txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58968264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com