142

基本的に、BeautifulSoupを使用して、Webページに表示されるテキストを厳密に取得したいと思います。たとえば、このWebページは私のテストケースです。そして、私は主に本文(記事)と、たぶんいくつかのタブ名をあちこちで取得したいと思っています。私はこのSOの質問<script>で、私が望まない多くのタグとhtmlコメントを返す提案を試しました。findAll()Webページに表示されるテキストを取得するために、関数に必要な引数を理解できません。

では、スクリプト、コメント、CSSなどを除くすべての表示テキストをどのように見つける必要がありますか?

4

10 に答える 10

271

これを試して:

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))
于 2009-12-31T00:06:12.410 に答える
39

@jbochiからの承認された回答は私には機能しません。str()関数呼び出しは、BeautifulSoup要素の非ASCII文字をエンコードできないため、例外を発生させます。これは、サンプルWebページを表示可能なテキストにフィルタリングするためのより簡潔な方法です。

html = open('21storm.html').read()
soup = BeautifulSoup(html)
[s.extract() for s in soup(['style', 'script', '[document]', 'head', 'title'])]
visible_text = soup.getText()
于 2013-11-04T00:35:55.970 に答える
34
import urllib
from bs4 import BeautifulSoup

url = "https://www.yahoo.com"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)

# kill all script and style elements
for script in soup(["script", "style"]):
    script.extract()    # rip it out

# get text
text = soup.get_text()

# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
# drop blank lines
text = '\n'.join(chunk for chunk in chunks if chunk)

print(text.encode('utf-8'))
于 2014-07-26T06:54:26.090 に答える
11

私はBeautifulSoupを使用してレンダリングされたコンテンツを取得することを完全に尊重していますが、ページ上のレンダリングされたコンテンツを取得するための理想的なパッケージではない場合があります。

レンダリングされたコンテンツ、または一般的なブラウザで表示されるコンテンツを取得する場合にも、同様の問題が発生しました。特に、以下のような単純な例で作業するために、おそらく非定型のケースがたくさんありました。この場合、表示できないタグはスタイルタグにネストされており、チェックした多くのブラウザでは表示されません。クラスタグ設定の表示をnoneに定義するなど、他のバリエーションもあります。次に、このクラスをdivに使用します。

<html>
  <title>  Title here</title>

  <body>

    lots of text here <p> <br>
    <h1> even headings </h1>

    <style type="text/css"> 
        <div > this will not be visible </div> 
    </style>


  </body>

</html>

上記の解決策の1つは次のとおりです。

html = Utilities.ReadFile('simple.html')
soup = BeautifulSoup.BeautifulSoup(html)
texts = soup.findAll(text=True)
visible_texts = filter(visible, texts)
print(visible_texts)


[u'\n', u'\n', u'\n\n        lots of text here ', u' ', u'\n', u' even headings ', u'\n', u' this will not be visible ', u'\n', u'\n']

このソリューションには確かに多くの場合アプリケーションがあり、一般的には非常にうまく機能しますが、上記のhtmlでは、レンダリングされていないテキストが保持されます。SOを検索した後、いくつかの解決策がここに現れました。BeautifulSoupget_textはすべてのタグとJavaScript を削除しません。ここでは、Pythonを使用してHTMLをプレーンテキストにレンダリングします。

html2textとnltk.clean_htmlの両方のソリューションを試しましたが、タイミングの結果に驚いたので、後世のための答えが必要だと思いました。もちろん、速度はデータの内容に大きく依存します...

@Helgeからのここでの1つの答えは、すべてのもののnltkを使用することについてでした。

import nltk

%timeit nltk.clean_html(html)
was returning 153 us per loop

レンダリングされたhtmlで文字列を返すことは本当にうまくいきました。このnltkモジュールは、html2textよりも高速でしたが、おそらくhtml2textの方が堅牢です。

betterHTML = html.decode(errors='ignore')
%timeit html2text.html2text(betterHTML)
%3.09 ms per loop
于 2013-11-05T19:37:08.120 に答える
4

BeautifulSoupを使用すると、コードが少なくて済み、空の行やがらくたなしで文字列を取得するのが最も簡単な方法です。

tag = <Parent_Tag_that_contains_the_data>
soup = BeautifulSoup(tag, 'html.parser')

for i in soup.stripped_strings:
    print repr(i)
于 2017-05-01T03:44:42.800 に答える
4

パフォーマンスが気になる場合は、もう1つのより効率的な方法があります。

import re

INVISIBLE_ELEMS = ('style', 'script', 'head', 'title')
RE_SPACES = re.compile(r'\s{3,}')

def visible_texts(soup):
    """ get visible text from a document """
    text = ' '.join([
        s for s in soup.strings
        if s.parent.name not in INVISIBLE_ELEMS
    ])
    # collapse multiple spaces to two spaces.
    return RE_SPACES.sub('  ', text)

soup.stringsはイテレータであり、NavigableString複数のループを経由せずに親のタグ名を直接確認できるように戻ります。

于 2017-06-18T03:26:18.457 に答える
3

私は完全に美しいスープを使用することをお勧めしますが、誰かが何らかの理由で不正な形式のhtmlの表示部分(たとえば、Webページのセグメントまたは行だけがある場合)を表示しようとしている場合は、次のようになります<>タグの間のコンテンツを削除します:

import re   ## only use with malformed html - this is not efficient
def display_visible_html_using_re(text):             
    return(re.sub("(\<.*?\>)", "",text))
于 2015-05-03T20:39:31.037 に答える
2

タイトルはタグ内にあり、タグとIDが「article」 のタグ<nyt_headline>内にネストされています。<h1><div>

soup.findAll('nyt_headline', limit=1)

動作するはずです。

記事の本文はタグ内にあり、タグはID「articleBody」<nyt_text>のタグ内にネストされています。<div>要素内<nyt_text> では、テキスト自体が<p> タグ内に含まれています。画像はこれらの<p>タグ内にありません。構文を試すのは難しいですが、実際のスクレイプは次のようになると思います。

text = soup.findAll('nyt_text', limit=1)[0]
text.findAll('p')
于 2009-12-20T18:40:54.353 に答える
0

このケースを処理する最も簡単な方法は、を使用することgetattr()です。この例をニーズに合わせることができます。

from bs4 import BeautifulSoup

source_html = """
<span class="ratingsDisplay">
    <a class="ratingNumber" href="https://www.youtube.com/watch?v=oHg5SJYRHA0" target="_blank" rel="noopener">
        <span class="ratingsContent">3.7</span>
    </a>
</span>
"""

soup = BeautifulSoup(source_html, "lxml")
my_ratings = getattr(soup.find('span', {"class": "ratingsContent"}), "text", None)
print(my_ratings)

"3.7"これにより、タグオブジェクト内にテキスト要素<span class="ratingsContent">3.7</span>が存在する場合はそれが検出されますが、デフォルトでは存在NoneTypeしない場合に検出されます。

getattr(object, name[, default])

オブジェクトの名前付き属性の値を返します。名前は文字列でなければなりません。文字列がオブジェクトの属性の1つの名前である場合、結果はその属性の値になります。たとえば、getattr(x、'foobar')はx.foobarと同等です。名前付き属性が存在しない場合、指定されている場合はデフォルトが返され、存在しない場合はAttributeErrorが発生します。

于 2020-01-13T21:59:29.813 に答える
0
from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib.request
import re
import ssl

def tag_visible(element):
    if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
        return False
    if isinstance(element, Comment):
        return False
    if re.match(r"[\n]+",str(element)): return False
    return True
def text_from_html(url):
    body = urllib.request.urlopen(url,context=ssl._create_unverified_context()).read()
    soup = BeautifulSoup(body ,"lxml")
    texts = soup.findAll(text=True)
    visible_texts = filter(tag_visible, texts)  
    text = u",".join(t.strip() for t in visible_texts)
    text = text.lstrip().rstrip()
    text = text.split(',')
    clean_text = ''
    for sen in text:
        if sen:
            sen = sen.rstrip().lstrip()
            clean_text += sen+','
    return clean_text
url = 'http://www.nytimes.com/2009/12/21/us/21storm.html'
print(text_from_html(url))
于 2020-03-02T09:52:46.870 に答える