【问题标题】:Beautiful Soup (Python)美丽的汤(Python)
【发布时间】:2014-07-30 18:35:13
【问题描述】:

我正在尝试访问 p 标签之间的餐厅列表。

<p class="openclosemonth" id="May2014">May, 2014</p>

<p>
<strong>CLOSED:</strong><br />
-- Haveli, Cambridge (Inman Square), MA<br />
-- Ma Soba, Boston (Beacon Hill), MA<br />
-- Milestone, Wellesley, MA<br />
-- Scosso, Peabody, MA<br />
-- Sonny Noto's, East Boston, MA<br />
-- Viva Mexican Grill, Wayland, MA<br />
</p>

<p>
<strong>OPEN:</strong><br />
-- The Abbey, Cambridge, MA<br />
-- The Bancroft, Burlington, MA<br />
-- Beantown Pho and Grill, Boston (Back Bay), MA<br />
-- The Briar Rose, Hyde Park, MA<br />
-- Caffe Nero, Boston, MA<br />
-- Cheeburger Cheeburger, Swampscott, MA<br />
</p>

关于如何提取所需数据的任何建议?

谢谢!

【问题讨论】:

  • 我建议使用 BeautifulSoup ;-) 到目前为止你有什么特别的困难吗?

标签: python beautifulsoup


【解决方案1】:

从&lt;p&gt; 标记中取出所有文本,去掉空格,跳过空的内容,然后跳过第一个:

for para in soup.find_all('p'):
    if para.strong is not None:
        print para.strong.get_text()
        lines = filter(None, (t.strip() for t in para.find_all(text=True)))[1:]
        print '\n'.join(lines)
        print

我对@9​​87654323@ 子标签进行了测试,以仅选择那些特定段落。

对于您的输入,这给出了:

>>> for para in soup.find_all('p'):
...     if para.strong is not None:
...         print para.strong.get_text()
...         lines = filter(None, (t.strip() for t in para.find_all(text=True)))[1:]
...         print '\n'.join(lines)
...         print
... 
CLOSED:
-- Haveli, Cambridge (Inman Square), MA
-- Ma Soba, Boston (Beacon Hill), MA
-- Milestone, Wellesley, MA
-- Scosso, Peabody, MA
-- Sonny Noto's, East Boston, MA
-- Viva Mexican Grill, Wayland, MA

OPEN:
-- The Abbey, Cambridge, MA
-- The Bancroft, Burlington, MA
-- Beantown Pho and Grill, Boston (Back Bay), MA
-- The Briar Rose, Hyde Park, MA
-- Caffe Nero, Boston, MA
-- Cheeburger Cheeburger, Swampscott, MA

【讨论】:

  • 感谢您回答我的问题。我知道很多人希望我花很长时间仔细阅读 Beautiful Soup 文档,我通常会这样做,但由于时间限制,我无法这次。此外,这不是家庭作业或其他任何东西——只是一个个人项目。
【解决方案2】:

Python3兼容版本使用简单方法。

for para in soup.find_all('p'):
    if para.strong is not None:
        for t in para.find_all(text=True):
            print (t.strip())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多