2015-06-01 14 views
5

Dưới đây là những gì tôi có cho đến nay:Hủy bỏ tất cả các phong cách, kịch bản, và các thẻ html từ một trang html

from bs4 import BeautifulSoup 

def cleanme(html): 
    soup = BeautifulSoup(html) # create a new bs4 object from the html data loaded 
    for script in soup(["script"]): 
     script.extract() 
    text = soup.get_text() 
    return text 
testhtml = "<!DOCTYPE HTML>\n<head>\n<title>THIS IS AN EXAMPLE </title><style>.call {font-family:Arial;}</style><script>getit</script><body>I need this text captured<h1>And this</h1></body>" 

cleaned = cleanme(testhtml) 
print (cleaned) 

này đang nỗ lực để loại bỏ các script

+1

kết quả mong muốn của bạn là gì? –

Trả lời

5

Dường như bạn gần như có nó. Bạn cũng cần phải loại bỏ các thẻ html và mã tạo kiểu css. Đây là giải pháp của tôi (tôi cập nhật các chức năng):

def cleanMe(html): 
    soup = BeautifulSoup(html) # create a new bs4 object from the html data loaded 
    for script in soup(["script", "style"]): # remove all javascript and stylesheet code 
     script.extract() 
    # 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) 
    return text 
1

Nếu bạn muốn có một giải pháp nhanh chóng và dơ bẩn bạn ca sử dụng:

re.sub(r'<[^>]*?>', '', value) 

Để thực hiện tương đương với strip_tags trong php. Đó có phải là những gì bạn muốn không?

7

Bạn có thể sử dụng decompose để xóa hoàn toàn các thẻ khỏi tài liệu và máy phát điện stripped_strings để truy xuất nội dung thẻ.

def clean_me(html): 
    soup = BeautifulSoup(html) 
    for s in soup(['script', 'style']): 
     s.decompose() 
    return ' '.join(soup.stripped_strings) 

>>> clean_me(testhtml) 
'THIS IS AN EXAMPLE I need this text captured And this' 
Các vấn đề liên quan