在 beautifulsoup/python 中查找具有特定文本的标签索引

Find index of tag with certain text in beautifulsoup/python

我有一个简单的 4x2 html table,其中包含有关 属性 的信息。

我正在尝试提取值 1972,它位于 Year Built 的列标题下。如果找到所有标签 td,如何提取包含文本 Year Built 的标签的索引?

因为一旦找到该索引,我只需添加 4 即可找到包含值 1972.

的标签

这里是 html:

<table>
    <tbody>
        <tr>
            <td>Building</td>
            <td>Type</td>
            <td>Year Built</td>
            <td>Sq. Ft.</td>
        </tr>
        <tr>
            <td>R01</td>
            <td>DWELL</td>
            <td>1972</td>
            <td>1166</td>
        </tr>   
    </tbody>
</table>

例如,我知道如果我的输入是索引 2 并且我的输出是该标签的文本 Year Built,我可以这样做:

from bs4 import BeautifulSoup
soup = BeautifulSoup(myhtml)
td_list = soup.find_all('td')
print td_list[2].text

但是我如何使用文本 Year Built 的输入来获取索引 2 的输出?

如果您的 table 有静态方案,最好使用行索引和列索引。试试这个:

rows = soup.find("table").find("tbody").find_all("tr")
print rows[1].find_all("td")[2].get_text()

或者,如果您只想查找包含 "Year Built" 的标签的索引号:

from bs4 import BeautifulSoup
soup = BeautifulSoup(myhtml)
td_list = soup.find_all('td')
i = 0
for elem in td_list:
    if elem.text == 'Year Built':
        ind = i
    i += 1
print td_list[ind].text

您的内容存储在文件名中。
请尝试:

In [3]: soup = BeautifulSoup(open("filename"))
In [4]: print soup.find_all('td')[2].string
Year Built

转成dict并得到值:

from bs4 import BeautifulSoup
table_data = [[cell.text for cell in row("td")] for row in BeautifulSoup(myhtml)("tr")]
dict = dict(zip(table_data[0], table_data[1]))
print dict['Year Built']