【发布时间】:2020-04-13 03:43:46
【问题描述】:
我正在尝试使用 Python 3 和 BeautifulSoup 4 获取从该页面下载 xlsx 文件的 URL:https://psnc.org.uk/funding-and-statistics/funding-distribution/retained-margin-category-m/
我需要获取最新文件的 url,该文件位于 <div> 内的 <p> 标记列表中的索引 0 处,我可以在控制台中使用 JS 获取它,如下所示:
var link = document.getElementsByClassName("toggle_container")[2].children[1].children[0].href
如果我使用BS4获取页面上的所有个<p>标签,我想要的链接在列表中:
import urllib
import requests
from bs4 import BeautifulSoup
cat_m_site = "https://psnc.org.uk/funding-and-statistics/funding-distribution/retained-margin-category-m/"
page = requests.get(cat_m_site)
soup = BeautifulSoup(page.text, 'html.parser')
p_elements = soup.find_all('p')
for item in p_elements:
print(item)
如果我尝试通过获取包含链接的 <div> 来重现 JS 解决方案,则应该有一个包含 29 个 <p> 元素的列表,但该列表为空:
import urllib
import requests
from bs4 import BeautifulSoup
cat_m_site = "https://psnc.org.uk/funding-and-statistics/funding-distribution/retained-margin-category-m/"
page = requests.get(cat_m_site)
soup = BeautifulSoup(page.text, 'html.parser')
divs = soup.find_all('div', {'class':'toggle_container'})
children = divs[2].findChildren("p", recursive=True)
for child in children:
print(child)
我更喜欢这种方式,因为我“知道”链接将位于此 div 的第 0 个元素中,但我觉得我缺少关于 findChildren 方法的一些内容。
【问题讨论】:
-
该页面是否使用 javascript 来动态创建这些元素?如果是这样,就不能使用requests来获取页面内容;你需要一些支持 javascript 的东西,比如 Selenium。
-
这个正确的网址是:psnc.org.uk/funding-and-statistics/pharmacy-funding/… 您提供的网址没有指向 xlsx 文件的链接。
-
@cgte - 抱歉,也许我的问题不够清楚。我提供的 url 包含指向
<div class="toggle_container">元素之一中大约 29 个 xlsx 文件的链接。链接的文本是“类别 M:产品和价格”
标签: python beautifulsoup