【问题标题】:Open online txt file using python codecs.open使用 python codecs.open 打开在线 txt 文件
【发布时间】:2019-04-23 04:07:05
【问题描述】:

我正在尝试使用 codecs.open 打开一个在线 txt 文件。我现在的代码是:

url = r'https://www.sec.gov/Archives/edgar/data/20/0000893220-96-000500.txt'
soup = BeautifulSoup(codecs.open(url, 'r',encoding='utf-8'), "lxml")

但是,Python 一直提示 OSError:

OSError: [Errno 22] Invalid argument: 'https://www.sec.gov/Archives/edgar/data/20/0000893220-96-000500.txt'

我尝试将“/”替换为“\”。它仍然不起作用。有什么办法可以解决吗?由于我有数千个要打开的链接,我不太想将在线文本文件下载到我的本地驱动器中。

如果有人能在这里提供帮助,我将不胜感激。

谢谢!

【问题讨论】:

  • codecs.open 采用文件名,而不是 url。
  • 谢谢,@larsks!我知道了。由于我想用beautifulsoup来解析txt格式写的html。有什么办法吗?
  • 使用http.client.HTTPConnection,您可以收到HTTPResponse,它可以被包装在codecs.EncodedFile 中(作为类似文件的对象)。

标签: python python-3.x text beautifulsoup codec


【解决方案1】:

你在想这样的事情吗?

`from urllib.request import urlopen
url = urlopen('https://www.sec.gov/Archives/edgar/data/20/0000893220-96- 000500.txt')
 html = url.read().decode('utf-8')
 file = open('yourfile.txt', 'r')
 file.read(html)
 file.close`

【讨论】:

    猜你喜欢
    • 2017-05-13
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 2016-01-31
    • 2022-10-13
    相关资源
    最近更新 更多