0

我想从给定的链接中检索 pdf 文件。命令行输出显示文件已保存在指定位置

import os
myPath = 'C:\\Documents'
filename = 'test1.pdf'
url = 'http://www.ha.org.hk/visitor/ha_view_content.asp?content_id=253124&lang=ENG'
fullfilename = os.path.join(myPath, filename)
urlretrieve(url, fullfilename)

>>> ('C:\\Documents\\test1.pdf', <http.client.HTTPMessage object at 0x016E0BB0>)

但是,当我转到文件目录时,test1.pdf 看起来已损坏。

下载的文件大小只有 1 KB,但实际文件应该在 4MB 左右。

4

2 回答 2

0

这个问题措辞不好。

但是我终于得到了一个可行的解决方案。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import pandas as pd
from bs4 import BeautifulSoup
from urllib.request import urlretrieve



driver = webdriver.Chrome(executable_path='chromedriver_win32/chromedriver.exe')

# open the download link, note that download link doesn't show the pdf url yet
driver.get('http://www.ha.org.hk/visitor/ha_view_content.asp?content_id=253237&lang=ENG')

# retrieve the current url once the previous url is opened, which should contain the pdf url
urlretrieve(driver.current_url)


于 2019-08-18T14:39:25.903 回答
0

您尝试从中下载 pdf 返回的 url = ' http://www.ha.org.hk/visitor/ha_view_content.asp?content_id=253124&lang=ENG '

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>HA</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link href="/visitor/v3/css/style-en.css" rel="stylesheet" type="text/css" />
        <script language="javascript" src="/visitor/v3/script/stylesheet.js" type="text/javascript"></script>
        <script language="javascript" type="text/javascript" src="/visitor/v3/common/js/function.js"></script>
        <script language="JavaScript" src="common_functions.js"></script>
    </head>
    <body id="iframebody">
        <div id="contentarea">
            <script>window.open('/haho/ho/bssd/KCCTE105218BTSa.pdf', '_self');</script>
        </div>
    </body>
</html>

由 urlretrieve(url, fullfilename) 下载并保存在文件中。这就是文件大小只有 1 KB 的原因。

你可以试试这个 url,' http://www.ha.org.hk/haho/ho/bssd/KCCTE105218BTSa.pdf ',它是一个重定向或从上述请求的输出中创建它。

于 2019-08-18T14:28:36.037 回答