![](/img/trans.png)
[英]Best way to strip everything except numbers and decimal points from a string in Python
[英]Best way to strip out everything but text from a webpage?
我正在尋找一個html頁面,只是在該頁面上提取純文本。 有人知道在python中這樣做的好方法嗎?
我想從字面上刪除所有內容,只留下文章的文本以及標簽之間的其他文本。 JS,css等......走了
謝謝!
如果它們在頁面中(未鏈接),則第一個答案不會刪除CSS或JavaScript標記的主體。 這可能會更接近:
def stripTags(text):
scripts = re.compile(r'<script.*?/script>')
css = re.compile(r'<style.*?/style>')
tags = re.compile(r'<.*?>')
text = scripts.sub('', text)
text = css.sub('', text)
text = tags.sub('', text)
return text
你可以試試相當優秀的美味湯
f = open("my_source.html","r")
s = f.read()
f.close()
soup = BeautifulSoup.BeautifulSoup(s)
txt = soup.body.getText()
但請注意:從任何解析嘗試中得到的回報都將受到“錯誤”的影響。 糟糕的HTML,糟糕的解析和一般的意外輸出。 如果您的源文檔是眾所周知的並且很好地呈現,那么您應該沒問題,或者至少能夠解決其中的特性問題,但如果它只是“在互聯網上”發現的一般內容,那么期待各種奇怪和奇妙的異常值。
按照這里 :
def remove_html_tags(data):
p = re.compile(r'<.*?>')
return p.sub('', data)
正如他在文章中指出的那樣,“re模塊需要導入才能使用正則表達式”。
lxml.html模塊值得考慮。 但是,需要一些按摩來刪除CSS和JavaScript:
def stripsource(page):
from lxml import html
source = html.fromstring(page)
for item in source.xpath("//style|//script|//comment()"):
item.getparent().remove(item)
for line in source.itertext():
if line.strip():
yield line
如果在生成空格的標記周圍沒有任何空格,則可以簡單地連接所產生的行,但是這可能會丟失重要的字邊界。
您可能還希望迭代<body>
標記,具體取決於您的要求。
我也會推薦BeautifulSoup,但我建議使用類似於這個問題的答案,我會在這里復制那些不想看的人:
soup = BeautifulSoup.BeautifulSoup(html)
texts = soup.findAll(text=True)
def visible(element):
if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
return False
elif re.match('<!--.*-->', str(element)):
return False
return True
visible_texts = filter(visible, texts)
我在這個頁面上嘗試了它,它運行得很好。
這是我發現剝離CSS和JavaScript的最簡潔最簡單的解決方案:
''.join(BeautifulSoup(content).findAll(text=lambda text:
text.parent.name != "script" and
text.parent.name != "style"))
Matthew Flaschen的 https://stackoverflow.com/a/3002599/1203188
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.