【问题标题】:Get the contents(full of text) from the paragraph beautiful soup从段落美汤中获取内容(全文)
【发布时间】:2014-11-03 07:29:06
【问题描述】:

我想从新闻网页中提取段落的内容(完整的文本),我有一组 url,它应该只从中提取段落的内容。当我使用下面的代码时,它会给我整个 html 页面。
这是我的代码

import urllib2
import urllib
from cookielib import CookieJar
from bs4 import BeautifulSoup
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
p = opener.open("http://www.nytimes.com/2014/09/09/world/europe/turkey-is-courted-by-us-to-help-         fight-isis.html?module=Search&mabReward=relbias%3Aw%2C%7B%222%22%3A%22RI%3A18%22%7D&_r=0")
print p.read()
soup = BeautifulSoup(p)
content = soup.find('p', attrs= {'class' : 'story-body-text story-content'})
print content

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    这是因为您有 print p.read() 行打印出整个 HTML 页面。

    要获取文章文本,请通过id 找到它,然后是文章中的所有段落。

    使用CSS Selector的示例:

    soup = BeautifulSoup(p)
    print ''.join(p.text for p in soup.select('article#story p.story-content'))
    

    打印:

    ANKARA, Turkey —  The Obama administration on Monday began the work of trying to determine
    ...
    

    仅供参考,article#story p.story-content 将匹配 article 标记内具有 story-content 类的所有 p 标记和 story id。

    【讨论】:

    • p.text.encode('utf-8') 如果它在您的 IDE 中打印不好。
    猜你喜欢
    • 2019-08-12
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    相关资源
    最近更新 更多