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

标签 python beautifulsoup python-requests shutil urllib3

我使用的是 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/

相关文章:

python - 我如何使用try&检查所有异常,但在python 2.7中没有pep8警告时除外?

python - Simple Web Scraper 不打印任何内容。问题是什么?

python-requests,找到正确的编码

python - Mac OS X El Capitan - Scrapy/Python 导入错误 : cannot import name xmlrpc_client

python - 删除 First_Name 行中的重复项,但附加 Last_Name 的集合

python - TypeError from use of "|"in re.search ("RE"|"RE"|"RE", string)

python - 访问小部件窗口beautifulsoup python mechanize

python - 提取文本 :after an element with Beautiful Soup

python - 无法使用 Python requests lib POST 文件附件和数据参数

python - HTTPSConnectionPool SSL错误证书验证失败