【问题标题】:Selecting nested third child in BeautifulSoup在 BeautifulSoup 中选择嵌套的第三个孩子
【发布时间】:2020-01-18 23:39:18
【问题描述】:

我有以下 HTML 部分,需要用 BeautifulSoup 提取 2.56% 的值。

<div class="box boxRatio">
    <h2 class="sectHed">Dividend Yield Range, Past 5 Years</h2>
    <table class="rangeModTable">
    <tr>
        <td class="col1">Minimum</td>
        <td class="col2">

                1.82%

        </td>
        <td class="col3">Jan 26 2018</td>
    </tr>
    <tr>
        <td class="col1">Maximum</td>
        <td class="col2">

                3.77%

        </td>
        <td class="col3">Oct 08 2019</td>
    </tr>
    <tr>
        <td class="col1">Average</td>
        <td class="col2">

                2.56%

        </td>
        <td class="col3"></td>
    </tr>
    </table>
</div>

我正在使用

divyield_box = soup.find(".boxRatio > .col2:nth-of-type(2)")

我不断收到 AttributeError: 'NoneType' object has no attribute 'text'

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    CSS 选择器与函数 .select().select_one() 一起使用,而不是 .find()

    你可以使用:

    value = soup.select_one(".rangeModTable tr:nth-of-type(3) .col2").get_text(strip=True)
    print(value)
    

    打印:

    2.56%
    

    或者如果你想从包含文本“平均”的行中选择值,你可以使用这个:

    value = soup.select_one('tr:has(td:contains("Average")) .col2').get_text(strip=True)
    print(value)
    

    【讨论】:

    • 谢谢,但是如何将值存储在变量中而不是打印?
    • Traceback(最近一次调用最后一次):文件“....”,第 14 行,在 divyild = divyild_box.text.strip() AttributeError: 'unicode' object has no attribute'文字'
    • @p3nd0l0 你在用 Python2 吗?我不知道你的整个脚本,但你可以试试divyield_box.get_text(strip=True)
    【解决方案2】:

    试试 SimplifiedDoc 的解决方案。

    from simplified_scrapy.simplified_doc import SimplifiedDoc
    html='''
    <div class="box boxRatio">
        <h2 class="sectHed">Dividend Yield Range, Past 5 Years</h2>
        <table class="rangeModTable">
        <tr>
            <td class="col1">Minimum</td>
            <td class="col2">
                    1.82%
            </td>
            <td class="col3">Jan 26 2018</td>
        </tr>
        <tr>
            <td class="col1">Maximum</td>
            <td class="col2">
                    3.77%
            </td>
            <td class="col3">Oct 08 2019</td>
        </tr>
        <tr>
            <td class="col1">Average</td>
            <td class="col2">
                    2.56%
            </td>
            <td class="col3"></td>
        </tr>
        </table>
    </div>
    '''
    doc = SimplifiedDoc(html)
    value = doc.select('.box boxRatio').getElementByText('Average').next.text
    print (value)
    

    结果:

    2.56%
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      • 2021-06-16
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      相关资源
      最近更新 更多