【发布时间】: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