Python中的HTML文件解析

2024-10-06 12:34:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常长的html文件,它看起来就像-html file。我希望能够解析该文件,以便获得元组形式的信息。在

示例:

<tr>
      <td>Cech</td>
      <td>Chelsea</td>
      <td>30</td>
      <td>£6.4</td>
</tr>

上面的信息看起来像("Cech", "Chelsea", 30, 6.4)。但是,如果仔细查看我发布的link,我发布的html示例位于<h2>Goalkeepers</h2>标记下。我也需要这个标签。所以基本上结果元组看起来像("Cech", "Chelsea", 30, 6.4, Goalkeepers)。再往下看,一批球员被分为中场、后卫和前锋。在

我试着用beauthulsoup和ntlk库,结果迷路了。现在我有了以下代码:

^{pr2}$

它只是剥离html文件中的所有标记并给出如下内容:

          Cech
          Chelsea
          30
          £6.4

虽然我可以写一段不好的代码来读取每一行并将其分配给一个元组。我不能想出任何解决方案,也可以合并播放器位置(字符串出现在<h2>标记中)。如有任何解决方案/建议,我们将不胜感激。在

我倾向于使用元组的原因是我可以使用解包,并计划用解包的值填充MySQl表。在


Tags: 文件代码标记信息示例htmlh2解决方案
1条回答
网友
1楼 · 发布于 2024-10-06 12:34:11
from bs4 import BeautifulSoup
from pprint import pprint

soup = BeautifulSoup(html)
h2s = soup.select("h2") #get all h2 elements
tables = soup.select("table") #get all tables

first = True
title =""
players = []
for i,table in enumerate(tables):
    if first:
         #every h2 element has 2 tables. table size = 8, h2 size = 4
         #so for every 2 tables 1 h2
         title =  h2s[int(i/2)].text
    for tr in table.select("tr"):
        player = (title,) #create a player
        for td in tr.select("td"):
            player = player + (td.text,) #add td info in the player
        if len(player) > 1: 
            #If the tr contains a player and its not only ("Goalkeaper") add it
            players.append(player)
    first = not first
pprint(players)

输出

^{pr2}$

相关问题 更多 >