【问题标题】:Beautiful Soup Get list elements not separating by commasBeautiful Soup 获取不以逗号分隔的列表元素
【发布时间】:2015-02-27 01:05:33
【问题描述】:

我正在尝试使用 Beautiful Soup 从网站解析城市列表

这是输出: MonroeMatthewsWaxhaw印度小径,马修斯

我需要的是: 梦露、马修斯、瓦克肖、印第安步道、马修斯

这是 HTML:

<div id="current_tab">
    <p class="view_label_type_geoserved" id="view_label_field_geoserved">Geographies Served</p>
    <ul>
        <li class="view_type_geoserved" id="view_field_geoserved">
            <p style="font-weight: bold; border-bottom: 1px dotted #CCC; font-size: .9em;">North Carolina (NC)<span style="float: right; font-size: 0.8em;">North Carolina (NC)</span></p>
            <p style="margin: 5px 0 3px 8px; border-bottom: 1px dotted #DDD; font-size:1em">Union<span style="float: right; font-size: 0.8em;">Union</span></p>
            <div class="view_type_geoserved">
                <table>
                    <tr>
                        <td style="width: 225px;">Monroe</td>
                        <td>Matthews</td></tr><tr>
                        <td style="width: 225px;">Waxhaw</td>
                        <td>Indian Trail</td>
                    </tr>
                </table>
            </div>
            </li>
                <p style="margin: 5px 0 3px 8px; border-bottom: 1px dotted #DDD; font-size:1em">Mecklenburg<span style="float: right; font-size: 0.8em;">Mecklenburg</span></p>
                <div class="view_type_geoserved">
                    <table>
                        <tr>
                            <td style="width: 225px;">Matthews</td><td></td>
                        </tr>
                    </table>
                </div>
            </li>
    </ul>
</div>

这是我用来输出的代码。

geoserved_muni = ', '.join(p.text for p in soup.findAll("div", {"class":"view_type_geoserved"}))
print geoserved_muni

在各个标签之间添加逗号时我缺少什么?

【问题讨论】:

    标签: python html beautifulsoup html-parsing


    【解决方案1】:

    div 中加入每个td 元素的文本:

    ', '.join(td.get_text(strip=True) for td in soup.select("div.view_type_geoserved > table tr > td") if td.text) 
    

    soup.select() 中的表达式是CSS selector

    经过测试,对我来说它会产生:

    Monroe, Matthews, Waxhaw, Indian Trail, Matthews
    

    【讨论】:

    • 这是完整的声明吗?它看起来还没有完成。
    • @ChrisTheDBA 抱歉,错过了右括号。感谢您的关注。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多