【问题标题】:BeautifulSoup Specify table column by number?BeautifulSoup 按数字指定表格列?
【发布时间】:2014-05-23 07:29:36
【问题描述】:

使用 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 是我网站上的一个页面,我基本上从 Wikipedia 复制了表格源以使抓取更简单。

谢谢!

evavid

【问题讨论】:

    标签: python html python-2.7 html-parsing beautifulsoup


    【解决方案1】:

    找到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)
    

    【讨论】:

    • 我没有意识到索引是内置的!
    猜你喜欢
    • 2018-04-17
    • 1970-01-01
    • 2014-06-28
    • 2020-12-27
    • 2020-09-09
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多