使用Python请求从URL下载PDF

2024-10-02 02:30:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一些脚本,将下载一个pdf从一个网址到我的电脑。 环顾互联网,我发现了一些我正在努力实现的例子。 我对Python非常陌生,代码中经常出现语法错误

import requests

url = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'
response = requests.get(url)

with open('C:\Users\User\PycharmProjects\PDFTest\FolderTest\dummy.pdf', 'wb') as f:
    f.write(response.content)

我收到的错误是:

  File "C:\Users\User\PycharmProjects\PDFTest\main.py", line 7
    with open('C:\Users\User\PycharmProjects\PDFTest\FolderTest\dummy.pdf', 'wb') as f:
                                                                          ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Process finished with exit code 1

我在一个虚拟机中运行所有的东西,如果这有任何影响的话,并且在Python3.9.1上运行。 我看到语法错误在逗号处,但我看到的一切都表明逗号是必须的。 任何帮助都将不胜感激。我的编程经验仅限于C++中的几个学期,还有大量的Python教程和视频。p>

我这个项目的最终目标(一旦我让这个部分工作起来)是在一个域中循环下载PDF。它们都存储为Https://www.examplesite.com/1000.pdf; ...com/1001.pdf。。。com/1002.pdf;等等,我想我可以通过在for循环中运行上面的内容并用++增加pdf URL(一个数字)来实现这一点。 谢谢你的帮助


Tags: comurlpdfresponsewwwwithopenrequests
2条回答

这是因为您在一个未被转换的字符串中使用了\。尝试在字符串前面使用\\或put和r

您也可以使用pathlib,我发现这更容易:

from pathlib import Path
import requests
filename = Path(r'C:\Users\User\PycharmProjects\PDFTest\FolderTest\dummy.pdf')
url = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'
response = requests.get(url)
filename.write_bytes(response.content)

出现您的问题是因为解释器难以解析文件的路径,因为它包含unicode转义字符

试一试

file_path = r'drive:\path\to\file'

这实际上是通过告诉解释器将其作为原始字符串读取来转义字符串中的特殊字符


用于替代实现

Tqdm为终端提供进度条

import os
from tqdm import tqdm
import requests

def download(lnk:str, fname:str):
    rq = requests.get(lnk,stream=True)
    totalsize = int(rq.headers['content-length'])
    chunksize = 1024
    if totalsize:
        print(f'\t{round(totalsize*10**-3,2):,} kb')
    with open(fname,'wb') as fobj:
        if totalsize:
            for b in tqdm(iterable=rq.iter_content(chunk_size=chunksize), total = totalsize/chunksize, unit = 'KB'):
                fobj.write(b)
        else:
            for b in tqdm(rq):
                fobj.write(b)
    os.startfile(fname)

相关问题 更多 >

    热门问题