使用Python从本地HTML文件创建一个具有名称和ID的CSV表



我是一个新手,尝试使用Python从本地HTML文件中获取数据,以提取名称和ID,并将其保存为CSV文件中的表。HTML如下:

<td>
<a href="https:............" data_id="45498" class="roster_user_name 
......
<span name="Clarence Alan" src="
</a>

</td>
<td>

88889999

</td>

我的代码有名单:

all_urls = [a['name']
for a in soup('span')
if a.has_attr('name')]
good_urls = list(set(all_urls))
print(len(good_urls))
good_urls

我不知道如何提取ID('8888999'(并将它们组合成一个两列表。

我对Python很陌生。谢谢你的回答。

我问您HTML是否有<tr>标记,您的回答显示tr标记的数量等于您想要抓取的条目的数量。

使用beautifulsoup,您可以循环浏览所有tr标签,并且可以提取每个tr标签所需的信息。

示例(将BeautifulSoup中的第一个参数替换为html字符串(

从bs4进口BeautifulSoup

soup = BeautifulSoup('<html> </html>', 'html.parser')
for row in soup.find_all('tr'):
name = row.find_all('td')[0].text
number = row.find_all('td')[1].text

这将遍历所有行并获取名称和编号。

然后您可以使用CSV库来存储数据。

示例

import csv
with open('file.csv', 'a+', newline='') as file:
writer = csv.writer(file)
writer.writerow(["COL1", "COL2"])

相关内容

最新更新