【问题标题】:Is there a way to get a file's URL that downloads automatically after a few seconds on a landing page with Python?有没有办法使用 Python 在登陆页面上几秒钟后自动下载文件的 URL?
【发布时间】:2020-07-29 09:01:55
【问题描述】:

在阅读了很多关于网络抓取以及如何使用 Python 跟踪 URL 重定向的帖子后,我终于不得不寻求您的帮助!

这是我尝试抓取的网站示例:http://xmaths.free.fr/1ES/cours/index.php

我的目标是自动下载 PDF 格式的练习及其更正。我已成功保存练习,但在尝试下载更正 PDF 文件时遇到问题。

例如,为了获得更正文件,网站提供此链接http://xmaths.free.fr/1ES/cours/corrige.php?nomexo=1ESpctgex01。当您单击它时,这将打开一个页面,告诉您您将访问更正。然后,几秒钟后,文件会自动打开,网址为 http://xmaths.free.fr/corrections/rMu623S1NA.pdf

我首先想到的是重定向。我使用了 requests.history 属性 (see this post) 但代码返回没有重定向。

这是我为尝试下载更正文件而编写的代码:

from bs4 import BeautifulSoup
import requests

correction_urls = ['http://xmaths.free.fr/1ES/cours/indications.php?nomexo=1ESderiex01', 'http://xmaths.free.fr/1ES/cours/indications.php?nomexo=1ESderiex02', 'http://xmaths.free.fr/1ES/cours/indications.php?nomexo=1ESderian02']

# Accessing each webpage stored in correction_urls list
for i, correction_url in enumerate(correction_urls):
    r = requests.get(correction_url)
    html_doc = r.text
    soup = BeautifulSoup(html_doc)
    
    # Iterate over each link on the page
    for link in soup.find_all("a"):
        href = link.get("href")
        
        # Identify links to corrections
        if str(href)[0:12] == "corrige.php?":
            
            # Build the full url and access it
            correction_pdf = "http://xmaths.free.fr/1ES/cours/" + href
            r = requests.get(correction_pdf)
            
            # Rename and save the pdf file
            with open("math_correction{}.pdf".format(i+1), "wb") as f:
                f.write(r.content)

通过这种方式,我无法到达 PDF 的最终链接,而只能到达文件打开之前页面的链接。

提前感谢您的帮助!

【问题讨论】:

    标签: python html pdf redirect web-scraping


    【解决方案1】:

    您可以从head内的<meta>标签中提取正确的路径:

    <META HTTP-EQUIV="Refresh" CONTENT="1 ; url=../../corrections/rMu623S1NA.pdf">
    

    import requests
    from bs4 import BeautifulSoup
    
    
    url = 'http://xmaths.free.fr/1ES/cours/corrige.php?nomexo=1ESpctgex01'
    soup = BeautifulSoup(requests.get(url).content, 'html.parser')
    r = requests.get('http://xmaths.free.fr/1ES/cours/' + soup.meta['content'].split(';')[-1].split('=')[-1])
    
    with open('document.pdf', 'wb') as f_out:
        f_out.write(r.content)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 2017-05-08
      • 2010-11-11
      • 2016-06-03
      相关资源
      最近更新 更多