BeautifulSoup按列号指定表格?

1 投票
1 回答
1065 浏览
提问于 2025-04-18 02:06

我正在使用Python 2.7和BeautifulSoup 4来从一个表格中抓取歌曲名称。

现在我的脚本可以找到表格行中的链接;我想知道怎么指定只想要第一列的内容?

理想情况下,我希望能通过调整数字来选择不同的列。

目前我的代码是这样的:

from bs4 import BeautifulSoup

import requests

r  = requests.get("http://evamsharma.finosus.com/beatles/index.html")

data = r.text

soup = BeautifulSoup(data)

for table in soup.find_all('table'):
    for row in soup.find_all('tr'):
        for link in soup.find_all('a'):
            print(link.contents)

我该如何在每个<tr>标签内索引<td>标签呢?

现在的URL是我网站上的一个页面,我基本上是从维基百科复制了表格的源代码,以便让抓取变得简单一些。

谢谢!

evamvid

1 个回答

1

在每个标签里面找到所有的标签,然后通过索引来获取你需要的那个标签:

index = 2
for table in soup.find_all('table'):
    for row in soup.find_all('tr'):
        try:
            td = row.find_all('td')[index]
        except IndexError:
            continue
        for link in td.find_all('a'):
            print(link.contents)

撰写回答