python - 使用 Python 网页抓取下载 PDF 不起作用

标签 python html web web-scraping beautifulsoup

这是我的代码:

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/

相关文章:

javascript - 如何将客户端 javascript 返回值传递给 ASP 经典服务器端

html - 忽略父宽度或填充

html/css 定位——像 facebook

http - www.domain.tld 与 domain.tld

http - URL中的参数分隔符,误用问号的情况

python - 使用交叉表时对值进行排序和删除

python - 无法安装 pysam 0.13

python - 由于缺少 UUID 模块,如何在 Python 2.4 中生成 UUID/GUID

Python3 -m 在Eclipse中运行配置

java - 如何使用记事本而不是使用 Eclipse 或任何 IDE 托管在 Red Hat 5 中开发的 Java 网站