Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python .requests()文件类型问题-Can';无法从内容交付网络获取PDF_Python_Pdf_Web Scraping_Request_Cdn - Fatal编程技术网

Python .requests()文件类型问题-Can';无法从内容交付网络获取PDF

Python .requests()文件类型问题-Can';无法从内容交付网络获取PDF,python,pdf,web-scraping,request,cdn,Python,Pdf,Web Scraping,Request,Cdn,我在获取PDF的内容时遇到了问题,因为它们由一个名为“加宽”的内容交付网络(CDN)托管 以下代码在网页中嵌入的PDF链接上成功 url = 'https://embed.widencdn.net/pdf/plus/widnr/kdlgedcepu/miss_surv_120117.pdf?u=7vkdxn' filepath = r"C:\Users\pathgoeshere\{}.pdf".format('test') if os.path.exists(fil

我在获取PDF的内容时遇到了问题,因为它们由一个名为“加宽”的内容交付网络(CDN)托管

以下代码在网页中嵌入的PDF链接上成功

url = 'https://embed.widencdn.net/pdf/plus/widnr/kdlgedcepu/miss_surv_120117.pdf?u=7vkdxn'
    
filepath = r"C:\Users\pathgoeshere\{}.pdf".format('test')
if os.path.exists(filepath):
    pass
else:
    r = requests.get(url)
    with open(filepath, 'wb') as f:
        f.write(r.content)
。。。但由于url指向内容交付网络,而不是pdf本身,因此请求不会返回所需的pdf;打开pdf文件时会引发错误


有人能帮忙抓取通过内容交付网络托管的pdf文件吗?

问题在于,您无法从CDN获得pdf,因为它将pdf封装在脚本中,该脚本自动设置密码并将您的请求重定向到另一个URL。为了下载pdf,您必须首先从标题中提取脚本标记,以找到指向pdf的url。然后,您必须使用与脚本设置完全相同的参数构建第二个请求:

  • 签名
  • 到期
  • 密钥对Id
  • 第二个请求是下载pdf

    导入操作系统
    导入请求
    将urllib.parse导入为urlparse
    从urllib.parse导入parseqs
    从urlextract导入urlextract
    从bs4导入BeautifulSoup
    url='1〕https://embed.widencdn.net/pdf/plus/widnr/rfazsshahb/Fall2017Waterfowl_GreenBay_Survey_Nov.pdf?u=7vkdxn'
    filepath=r'C:\Path\{}.pdf'。格式('test')
    如果os.path.存在(文件路径):
    通过
    其他:
    request=requests.get(url)
    html=BeautifulSoup(request.content)
    pdf_script=html.head.find('script',type=“text/javascript”).string
    #提取url
    提取器=URLExtract()
    url\u to\u pdf=提取器。查找\u url(pdf\u脚本)
    #解析URL
    parsed=urlparse.urlparse(url到pdf[0])
    #获取参数
    signature=parse_qs(parsed.query)['signature'][0]
    expires=int(parse_qs(parsed.query)['expires'][0])
    kip=parse_qs(parsed.query)['Key-Pair-Id'][0]
    url=parsed.scheme+“:/”+parsed.netloc+parsed.path
    #生成第二个请求
    pdf_request=requests.get(url,params={'Key-Pair-Id':kip,'Signature':Signature,'Expires':Expires})
    打印(pdf\U请求)
    将open(filepath,'wb')作为f:
    f、 编写(pdf_request.content)
    
    您可能需要安装urlextract、BeautifulSoup

    pip install beautifulsoup4
    pip install urlextract
    

    请注意,这不是通用解决方案,可能仅适用于此CDN。

    做得好!这是一个很好的回答;直接但解释性的。非常感谢。