在阅读了大量关于网页抓取以及如何使用Python跟踪URL重定向的帖子后,我终于不得不请求您的帮助
下面是一个我正试图抓取的网站的例子:http://xmaths.free.fr/1ES/cours/index.php
我的目标是自动下载PDF格式的练习及其更正。我已成功保存练习,但在尝试下载PDF文件时遇到问题
例如,为了获得更正文件,网站提供了以下链接http://xmaths.free.fr/1ES/cours/corrige.php?nomexo=1ESpctgex01。当您单击它时,会打开一个页面,告诉您将访问更正。然后,几秒钟后,文件自动打开,url为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的最终链接,而只能访问文件打开前页面的链接
提前感谢您的帮助
您可以从磁头内的
<meta>
标记中提取正确的路径:相关问题 更多 >
编程相关推荐