这是我的代码:
import os
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup
url = "https://mathsmadeeasy.co.uk/gcse-maths-revision/"
#If there is no such folder, the script will create one automatically
folder_location = r'E:\webscraping'
if not os.path.exists(folder_location):os.mkdir(folder_location)
response = requests.get(url)
soup= BeautifulSoup(response.text, "html.parser")
for link in soup.select("a[href$='.pdf']"):
#Name the pdf files using the last portion of each link which are unique in this case
filename = os.path.join(folder_location,link['href'].split('/')[-1])
with open(filename, 'wb') as f:
f.write(requests.get(urljoin(url,link['href'])).content)
关于为什么代码不下载我的任何文件格式数学修订网站的任何帮助。 谢谢。
最佳答案
查看页面本身,虽然它看起来可能是静态的,但事实并非如此。您尝试访问的内容被一些奇特的 JavaScript 加载所限制。我所做的评估就是简单地记录 BS4 实际获得的页面并在文本编辑器中打开它:
with open(folder_location+"\page.html", 'wb') as f:
f.write(response.content)
从外观上看,该页面正在用 JS 替换占位符,正如 HTML 文件的第 70 行注释所示: //interpolate json by replacement placeholders with variables
为了解决您的问题,BS4 似乎无法加载 Javascript。我建议查看 this answer对于有类似问题的人。我还建议查看 Scrapy如果您打算进行一些更复杂的网络抓取。
关于python - 使用 Python 网页抓取下载 PDF 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63010815/