【问题标题】:scraping using beautiful soup用美丽的汤刮
【发布时间】:2014-05-28 14:40:49
【问题描述】:

我正在使用 BeautifulSoup 抓取一篇文章。除了某个部分之外,我想刮掉文章正文中的所有 p 标签。我想知道是否有人可以提示我做错了什么?我没有收到错误,它只是没有呈现任何不同。目前它正在从不需要的部分中抓取单词“Print”并与其他 p 标签一起打印。

我想忽略的部分:soup.find("div", {'class': 'add-this'})

    url: http://www.un.org/apps/news/story.asp?NewsID=47549&Cr=burundi&Cr1=#.U0vmB8fTYig

    # Parse HTML of article, aka making soup
    soup = BeautifulSoup(urllib2.urlopen(url).read())

    # Retrieve all of the paragraphs
    tags = soup.find("div", {'id': 'fullstory'}).find_all('p')
    for tag in tags:
        ptags = soup.find("div", {'class': 'add-this'})
        for tag in ptags:
            txt.write(tag.nextSibling.text.encode('utf-8') + '\n' + '\n')
        else:
            txt.write(tag.text.encode('utf-8') + '\n' + '\n')

【问题讨论】:

  • 你明确地循环了ptags;这不是忽略它,而是忽略其他所有内容

标签: python python-2.7 web-scraping html-parsing beautifulsoup


【解决方案1】:

一种选择是只传递recursive=False,以免在fullstory div 的任何其他元素内搜索p 标签:

tags = soup.find("div", {'id': 'fullstory'}).find_all('p', recursive=False)
for tag in tags:
    print tag.text

这将只从 div 中获取顶级段落,打印完整的文章:

10 April 2014  The United Nations today called on the Government...
...
...follow up with the Government on these concerns.

【讨论】:

    猜你喜欢
    • 2021-01-15
    • 2020-12-13
    • 2019-03-13
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多