使用pyodide从URL下载文件?

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

我正在尝试将 python 脚本转换为与 pyodide 一起运行,但无法从 url 下载文件,或者对我来说或者确切地说,我无法获取或访问我想要下载的实际对象(pdf 或纯文本,目前两者都不适合我)。

我尝试过的代码如下所示:

url = 'https://d-nb.info/1205215212/04/text'

res = await pyfetch(url, mode="no-cors")
print(res.text)

pyfetch 返回一个获取响应对象,但是当我尝试使用 .text 实际获取文本时,我得到了以下信息:

<bound method FetchResponse.text of <pyodide.http.FetchResponse object at 0x28fa8a0>>

我试图找出它的含义,但没有成功。同样的方法也适用于 API 请求,所以我不确定为什么它在这里不起作用。也许是模式的问题,但如果我不添加 mode="no-cors" 我总是会收到网络错误。

我尝试过的替代方案如下:

from pyodide.http import open_url

url_contents = open_url(url)

url_contents.read()
print(url_contents)

它返回一个 io.StringIO 对象,但我也不确定如何从那里继续访问实际文本?更糟糕的是,我也想从这样的网址下载 PDF。任何帮助将非常感激。 (我通常使用 requests 和 wget 来执行此操作,效果很好,但不幸的是两者都不适用于 pyodide,这需要这样我才能在 jupyter-lite 环境中运行它)。

python download fetch pyodide
1个回答
0
投票

该问题是由于同源策略和安全限制造成的。当您使用 mode="no-cors" 时,您实际上是在发出跨源请求,而无法访问 JavaScript 中的响应内容,这可能就是您无法使用 .text 检索文本的原因。

要解决此问题,您可以使用 open_url 函数,但您需要正确读取 io.StringIO 对象中的内容。要下载 PDF,您应该使用适当的方法将内容保存到文件中。 这是一个例子:

from pyodide.http import open_url
import io
import urllib.request

url = 'https://d-nb.info/1205215212/04/text'

# Open the URL
url_contents = open_url(url)

if url_contents:
    if url_contents.info().get_content_type() == "text/plain":
        # If the content is plain text, read and print it
        text_content = url_contents.read()
        print(text_content)
    elif url_contents.info().get_content_type() == "application/pdf":
        # If the content is a PDF, save it to a file
        with open('downloaded.pdf', 'wb') as pdf_file:
            pdf_file.write(url_contents.read())

# Close the URL
url_contents.close()
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.