代码之家  ›  专栏  ›  技术社区  ›  RydallCooper

Python BeautifulSoup解析HTML时出错

  •  1
  • RydallCooper  · 技术社区  · 11 年前

    我在解析BeautifulSoup中的某些信息时遇到问题 here 。在我用模块抓取html代码之后 机械化 我正试图将我想要的最终结果集中在这一小段html上:

        <table style="padding-top:10px;">
            <tr><th>ISP:</th><td>Brighthouse Networks</td></tr>
            <tr><th>Services:</th><td><a href="/ip-services">None Detected</a></td></tr>
            <tr><th>City:</th><td>Miami</td></tr>
            <th>Region:</th><td>Florida</td>
            <tr><th>Country:</th><td>United States</td></tr>
        </table>
    

    现在我希望我的最终结果是这样的:

        ISP: Brighthouse Networks
        Services: None Detected
        City: Miami
        Region: Florida
        Country: United States
    

    我编写的脚本的解析部分是:

        soup = BeautifulSoup(html)
        table = soup.findall('table',{'style':'padding-top:10px;'})
        for t in table:
            print t.text
    

    然而,这并没有产生我上面列出的我想要的结果。非常感谢您的帮助。谢谢

    2 回复  |  直到 11 年前
        1
  •  1
  •   joaoricardo000    11 年前

    这项工作(:

    from bs4 import BeautifulSoup
    
    html = """<table style="padding-top:10px;">
        <tr><th>ISP:</th><td>Brighthouse Networks</td></tr>
        <tr><th>Services:</th><td><a href="/ip-services">None Detected</a></td></tr>
        <tr><th>City:</th><td>Miami</td></tr>
        <th>Region:</th><td>Florida</td>
        <tr><th>Country:</th><td>United States</td></tr>
    </table>"""
    
    soup = BeautifulSoup(html)
    table = soup.findAll('table', {"style":"padding-top:10px;"})[0]
    
    trs = table('tr')
    for tr in trs:
        print tr.th.text,
        print tr.td.text
    
    #and this for the 'Region'
    print table("th")[3].text,
    print table("td")[3].text
    

    输出:

    ISP: Brighthouse Networks
    Services: None Detected
    City: Miami
    Country: United States
    Region: Florida
    
        2
  •  1
  •   Pawel Miech    11 年前
    table = soup.find_all('table',attrs={'style':'padding-top:10px;'})
    

    应该会成功。

    find_all() 具有以下签名:

    find_all(name, attrs, recursive, text, limit, **kwargs)

    若将属性作为第二个参数传递,find_all希望它是字符串而不是字典。如果要将属性字典传递给find_all,则应将其传递为 attrs keyword argument .