BeautifulSoup で表示されているウェブページのテキストのみをスクレイピングする方法は? 質問する

BeautifulSoup で表示されているウェブページのテキストのみをスクレイピングする方法は? 質問する

BeautifulSoup基本的に、厳密に取得するために使用したい表示テキストウェブページ上で。例えば、このウェブページこれは私のテストケースです。そして私は主に本文(記事)といくつかのタブ名を取得したいだけです。私はこの提案を試しました質問ですたくさんの<script>タグとHTMLコメントが返されますが、これは望ましくありません。関数に必要な引数がわかりません。findAll()ウェブページ上の表示されているテキストのみを取得するためです。

では、スクリプト、コメント、CSS などを除いたすべての表示テキストを見つけるにはどうすればよいでしょうか?

ベストアンサー1

これを試して:

from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib.request


def tag_visible(element):
    if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
        return False
    if isinstance(element, Comment):
        return False
    return True


def text_from_html(body):
    soup = BeautifulSoup(body, 'html.parser')
    texts = soup.findAll(text=True)
    visible_texts = filter(tag_visible, texts)  
    return u" ".join(t.strip() for t in visible_texts)

html = urllib.request.urlopen('http://www.nytimes.com/2009/12/21/us/21storm.html').read()
print(text_from_html(html))

おすすめ記事