【发布时间】:2021-01-14 06:01:36
【问题描述】:
我正在使用一个 Python 模块来抓取一个站点,并在下面的代码中注意到它以不同的方式处理不同的表:
def player_stats(request, stat, numeric=False, s_index=False):
"""
"""
supported_tables = ["totals", "per_minute", "per_poss", "advanced",
"playoffs_per_game", "playoffs_totals", "playoffs_per_minute",
"playoffs_per_poss", "playoffs_advanced"]
if stat == "per_game":
soup = BeautifulSoup(request.text, "html.parser")
table = soup.find("table", id="per_game")
elif stat in supported_tables:
soup = BeautifulSoup(request.text, "html.parser")
comment_table = soup.find(text=lambda x: isinstance(x, NavigableString) and stat in x)
soup = BeautifulSoup(comment_table, "html.parser")
table = soup.find("table", id=stat)
else:
raise TableNonExistent
将使用的页面示例:https://www.basketball-reference.com/players/j/jamesle01.html
如果要执行soup.find_all("table"),则只会找到第一个表。上面的代码似乎在 HTML 中检查“cmets”,然后再次应用 BeautifulSoup。我有几个问题:
-
为什么找不到其他表?它们也是 HTML 标签(未注释掉),所以我很难理解其中的区别。
-
comment_table代码行的真正作用是什么?对我来说,它看起来像是在检查text属性,这些属性是NavigableStrings,包含supported_tables中的一个元素? -
如果我对上述内容是正确的,BeautifulSoup 如何简单地解析该文本块?是“魔法”还是该文本必须具有特定形式……因此,在这种情况下我们很幸运?
如果您需要更多信息来回答问题,请告诉我。谢谢!
【问题讨论】:
标签: python html python-3.x beautifulsoup