Python 解析HTML——为什么这个文档必须通过文本而不是标记来解析?
我使用的是一个Python模块,它对一个站点进行了清理,并在下面的代码中注意到,它以不同的方式处理不同的表:Python 解析HTML——为什么这个文档必须通过文本而不是标记来解析?,python,html,python-3.x,beautifulsoup,Python,Html,Python 3.x,Beautifulsoup,我使用的是一个Python模块,它对一个站点进行了清理,并在下面的代码中注意到,它以不同的方式处理不同的表: def player_stats(request, stat, numeric=False, s_index=False): """ """ supported_tables = ["totals", "per_minute", "per_poss&qu
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中的“注释”,然后再次应用BeautifulSoup。我有几个问题:
comment\u表
行代码真正在做什么?对我来说,它看起来像是在检查支持的\u表中包含元素的navigablesting
属性
如果您需要更多信息来回答问题,请告诉我。谢谢 不是这方面的专家,而是我的观察:
comment\u表
行的内容与您所说的差不多。我想补充一点,supported_tables
是预期的已注释表列表
注释\u表
,而不仅仅是一块文本;哪个BeautifulSoup
知道如何解析。
您可以通过以下方式进行验证:
Comment
是navigablesting
的一种类型
相当于
想象一下,一行又一行的代码都被强制放在一行中,不容易阅读,只需将注释标记放在已经格式化的代码的上面和下面就容易多了
想想“请评论一下这是怎么错的。他们仍然被评论掉了。这会帮助我改进我的回答。我投了更高的票。看起来你没有错——不确定其他人可能认为这有什么错。
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)
print(type(comment_table))