gpt4 book ai didi

Python BeautifulSoup 找不到表 ID

转载 作者:太空宇宙 更新时间:2023-11-03 15:08:42 24 4
gpt4 key购买 nike

我在使用 BeautifulSoup 抓取表格时遇到了一些麻烦。这是我的代码

from urllib.request import urlopen
from bs4 import BeautifulSoup

site = "http://www.sports-reference.com/cbb/schools/clemson/2014.html"
page = urlopen(site)
soup = BeautifulSoup(page,"html.parser")

stats = soup.find('table', id = 'totals')

In [78]: print(stats)
None

当我右键单击表格来检查元素时,HTML 看起来如我所料,但是当我查看源代码时,唯一 id = 'totals' 的元素被注释掉。有没有办法从注释的源代码中抓取表格?

我已经引用了this post但似乎无法复制他们的解决方案。

这是一个link to the webpage我感兴趣。我想抓取标有“总计”的表格并将其存储为数据框。

我对 Python、HTML 和网页抓取还比较陌生。任何帮助将不胜感激。

提前致谢。

迈克尔

最佳答案

注释是 BeautifulSoup 中的字符串实例。您可以使用 BeautifulSoup 的 find 方法和正则表达式来查找您要查找的特定字符串。获得字符串后,让 BeautifulSoup 解析该字符串即可。

换句话说,

import re
from urllib.request import urlopen
from bs4 import BeautifulSoup

site = "http://www.sports-reference.com/cbb/schools/clemson/2014.html"
page = urlopen(site)
soup = BeautifulSoup(page,"html.parser")

stats_html = soup.find(string=re.compile('id="totals"'))
stats_soup = BeautifulSoup(stats_html, "html.parser")

print(stats_soup.table.caption.text)

关于Python BeautifulSoup 找不到表 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44424690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com