beauthulsoup按数字指定表列?

2024-05-21 08:39:02 发布

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

使用python2.7和beautifulsoup4,我从一个表中抓取歌曲名称。在

现在,脚本在一个表的行中查找链接;如何指定我想要第一列?在

理想情况下,我可以切换数字,以改变哪些人被选中。在

现在代码如下:

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是我网站上的一个页面,我基本上从Wikipedia复制了表源代码,这样就简化了抓取。在

谢谢!在

依凡维德


Tags: in标记importfordatatablelinkall
1条回答
网友
1楼 · 发布于 2024-05-21 08:39:02

查找tr内的所有td标记,并通过索引获得所需的标记:

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)

相关问题 更多 >