【问题标题】:Extracting a value from html table using BeautifulSoup使用 BeautifulSoup 从 html 表中提取值
【发布时间】:2020-04-23 15:05:38
【问题描述】:

我正在尝试使用 bs4 从 html 表中提取值,但是表的结构是:

<td class="celda400" vAlign="center" align="right" width="100" bgColor="#DFEDFF" style="color:Black">
575,42
</td>

我感兴趣的值是 575,42,但是它没有要被提取的 bs4 使用的 id 或其他标识符。

如何调用这个值?或者在什么id下?

【问题讨论】:

    标签: python beautifulsoup html-parsing


    【解决方案1】:

    你可以试试。我想,你可以理解:

    from bs4 import BeautifulSoup
    
    html_doc = """
        <td class="celda400" vAlign="center" align="right" width="100" bgColor="#DFEDFF" style="color:Black">
        575,42
        </td>
        <td class="celda400" vAlign="center" align="right" width="100" bgColor="#DFEDFF" style="color:Black">
        875,42
        </td>
        """
    soup = BeautifulSoup(html_doc, 'lxml')
    
    all_td = soup.find_all('td', {'class':"celda400"})
    
    for td in all_td:
        value = td.text.strip()
        print(value)
    
    

    【讨论】:

    • 它可以工作,谢谢,因为我至少有 60 行类似的行,我现在需要的是创建一个循环。再次感谢您的帮助!
    • 快速提问,我在使用循环提取感兴趣的值时遇到问题,换句话说,我有兴趣从 50 行中提取所有数值(就像 575,42),类似于您在示例中创建的那个。您是否知道 bs4 中的某些内容可以使这项任务变得更轻松?
    【解决方案2】:

    您可以使用任何属性进行提取。例如,使用

    class = "celda400" 属性

    response.find('td', {'class':"celda400"}).string
    

    【讨论】:

    • 更好更干净,但我仍然看到整个数据。问题是我需要的唯一值是 575,42。你的推荐更干净,但仍然看到: 575,42 ,
    • 调用.string 应该只为您提供标签内的数据。如果这对您有帮助,请单击勾号接受答案:)
    • 谢谢!我相信value = soup.find('td', {'class':"celda400"}).text 有效,现在我正在处理循环,因为我有 60 行需要提取值。再次感谢您的帮助。
    【解决方案3】:

    另一种解决方案。

    from simplified_scrapy import SimplifiedDoc,req,utils
    html = '''
    <td class="celda400" vAlign="center" align="right" width="100" bgColor="#DFEDFF" style="color:Black">
    575,42
    </td>
    <td class="celda400" vAlign="center" align="right" width="100" bgColor="#DFEDFF" style="color:Black">
    575,43
    </td>
    '''
    doc = SimplifiedDoc(html)
    texts = doc.selects('td.celda400').text
    print (texts)
    

    结果:

    ['575,42', '575,43']
    

    这里有更多示例。 https://github.com/yiyedata/simplified-scrapy-demo/blob/master/doc_examples

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多