2016-05-04 8 views
2

からすべてのHTMLタグを削除します。パイソン、私は以下のコードでbeautifulsoup使用して、Webサイトからの記事のコンテンツにアクセスしようとしていた文字列

site= 'www.example.com' 
page = urllib2.urlopen(req) 
soup = BeautifulSoup(page) 
content = soup.find_all('p') 
content=str(content) 

コンテンツオブジェクトがそのページからメインのテキストのすべてが含まれています'p'タグ内にありますが、下の画像に示すように、出力内にはまだ他のタグがあります。 <>タグとタグ自体の一致するペアで囲まれたすべての文字を削除したいと思います。テキストだけが残るようにします。

私は以下の方法を試しましたが、うまくいかないようです。

' '.join(item for item in content.split() if not (item.startswith('<') and item.endswith('>'))) 

スティングの部分文字列を削除するにはどうすればよいですか?

for text in content.strings: 
    print(text) 

答えて

3

あなたは以下get_text()

for i in content: 
    print i.get_text() 

例からで使用することもできます。それは、このような> <など

enter image description here

1

あなたが使用する必要がstrings generator開始し、一定のパターンで終わりますdocs

>>> markup = '<a href="http://example.com/">\nI linked to <i>example.com</i>\n</a>' 
>>> soup = BeautifulSoup(markup) 
>>> soup.get_text() 
u'\nI linked to example.com\n' 
7

使用正規表現:

re.sub('<[^<]+?>', '', text) 

BeautifulSoupを使用する:(hereからソリューション)

import urllib 
from bs4 import BeautifulSoup 

url = "http://news.bbc.co.uk/2/hi/health/2284783.stm" 
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) 

NLTKを使用する:Pyparsingは、それが簡単でHTMLストリッパーを書くことができます

import nltk 
from urllib import urlopen 
url = "https://stackoverflow.com/questions/tagged/python"  
html = urlopen(url).read()  
raw = nltk.clean_html(html) 
print(raw) 
0

すべての開閉HTMLタグに一致するパターンを定義し、次にtそのパターンをサプレッサーとして使用して入力を変換します。これはまだ変換する&xxx; HTMLエンティティを離れる - あなたはそれを行うためにxml.sax.saxutils.unescapeを使用することができます。

source = """ 
<p><strong>Editors' Pick: Originally published March 22.<br /> <br /> Apple</strong> <span class=" TICKERFLAT">(<a href="/quote/AAPL.html">AAPL</a> - <a href="http://secure2.thestreet.com/cap/prm.do?OID=028198&amp;ticker=AAPL">Get Report</a><a class=" arrow" href="/quote/AAPL.html"><span class=" tickerChange" id="story_AAPL"></span></a>)</span> is waking up the echoes with the reintroduction of a&nbsp;4-inch iPhone, a model&nbsp;its creators hope will lead the company to victory not just in emerging markets, but at home as well.</p> 
<p>&quot;There's significant pent-up demand within Apple's base of iPhone owners who want a smaller iPhone with up-to-date specs and newer features,&quot; Jackdaw Research Chief Analyst Jan Dawson said in e-mailed comments.</p> 
<p>The new model, dubbed the iPhone SE, &quot;should unleash a decent upgrade cycle over the coming months,&quot; Dawson said.&nbsp;Prior to the iPhone 6 and 6 Plus, introduced in 2014, Apple's iPhones were small, at 3.5 inches and 4 inches tall, respectively, compared with models by Samsung and others that approached 6 inches.</p> 
<div class=" butonTextPromoAd"> 
<div class=" ym" id="ym_44444440"></div>""" 

from pyparsing import anyOpenTag, anyCloseTag 
from xml.sax.saxutils import unescape as unescape 
unescape_xml_entities = lambda s: unescape(s, {"&apos;": "'", "&quot;": '"', "&nbsp;":" "}) 

stripper = (anyOpenTag | anyCloseTag).suppress() 

print(unescape_xml_entities(stripper.transformString(source))) 

ができます:

Editors' Pick: Originally published March 22. Apple (AAPL - Get Report) is waking up the echoes with the reintroduction of a 4-inch iPhone, a model its creators hope will lead the company to victory not just in emerging markets, but at home as well. 
"There's significant pent-up demand within Apple's base of iPhone owners who want a smaller iPhone with up-to-date specs and newer features," Jackdaw Research Chief Analyst Jan Dawson said in e-mailed comments. 
The new model, dubbed the iPhone SE, "should unleash a decent upgrade cycle over the coming months," Dawson said. Prior to the iPhone 6 and 6 Plus, introduced in 2014, Apple's iPhones were small, at 3.5 inches and 4 inches tall, respectively, compared with models by Samsung and others that approached 6 inches. 

(そして将来的には、非としてサンプルテキストやコードを提供しないでください-copy-pasteable images)

0

ライブラリを使用するように制限されている場合は、htmlタグを削除するために以下のコードを使用します。

あなたが試したものを修正しました。アイデアありがとう

content="<h4 style='font-size: 11pt; color: rgb(67, 67, 67); font-family: arial, sans-serif;'>Sample text for display.</h4> <p>&nbsp;</p>" 


' '.join([word for line in [item.strip() for item in content.replace('<',' <').replace('>','> ').split('>') if not (item.strip().startswith('<') or (item.strip().startswith('&') and item.strip().endswith(';')))] for word in line.split() if not (word.strip().startswith('<') or (word.strip().startswith('&') and word.strip().endswith(';')))]) 
関連する問題

 関連する問題