【问题标题】:Find index of tag with certain text in beautifulsoup/python在beautifulsoup/python中查找带有特定文本的标签索引
【发布时间】:2016-01-10 18:27:03
【问题描述】:

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

我正在尝试提取值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 的输出?

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

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

    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
    

    【讨论】:

      【解决方案2】:

      将其转换为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']
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 2018-10-11
          • 2014-05-09
          • 2016-01-10
          • 2012-10-25
          • 2019-07-01
          • 2020-10-05
          • 1970-01-01
          • 2023-04-10
          • 2010-10-26
          相关资源
          最近更新 更多