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

问题描述 投票:1回答:1

我正在使用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文件并将其保存到本地驱动器?预先谢谢你。

python beautifulsoup python-requests shutil urllib3
1个回答
2
投票

'as'关键字用于导入。我测试了完整的代码段,并在这里进行了一些小的更改后就可以下载。

尝试将其声明为变量,而不是像这样:

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

out_file = open(out_file, 'wb')
shutil.copyfileobj(res, out_file)
© www.soinside.com 2019 - 2024. All rights reserved.