2015-06-09 3 views
1

Я передаю код HMTL в BeautifulSoup с помощью Python, и мой вывод ошибочен комментариями HTML. У меня есть этот скрипт python для удаления комментариев HTML, но он не удаляет HTML-комментарии, вложенные с комментариями CSS.Извлеките комментарии CSS и HTML из HTML doc (Python)

Мой код:

from bs4 import BeautifulSoup, Comment 

    input_text = "" 

    for line in open('output.txt'): 
      input_text+=line 

    soup = BeautifulSoup(input_text) 
    comments = soup.findAll(text=lambda text:isinstance(text, Comment)) 
    [comment.extract() for comment in comments] 
    print soup 

Например, он удаляет все HTML комментарии из моего тестового входа, за исключением:

<!-- /* Font Definitions */ @font-face {font-family:"Cambria Math"; panose-1:2 4 5 3 5 4 6 3 2 4;} @font-face {font-family:Calibri; panose-1:2 15 5 2 2 2 4 3 2 4;} @font-face {font-family:Verdana; panose-1:2 11 6 4 3 5 4 4 2 4;} @font-face {font-family:inherit;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {margin:0in; margin-bottom:.0001pt; font-size:12.0pt; font-family:"Times New Roman",serif;} a:link, span.MsoHyperlink {mso-style-priority:99; color:blue; text-decoration:underline;} a:visited, span.MsoHyperlinkFollowed {mso-style-priority:99; color:purple; text-decoration:underline;} span.EmailStyle17 {mso-style-type:personal-reply; font-family:"Calibri",sans-serif; color:#1F497D;} .MsoChpDefault {mso-style-type:export-only; font-family:"Calibri",sans-serif;} @page WordSection1 {size:8.5in 11.0in; margin:1.0in 1.0in 1.0in 1.0in;} div.WordSection1 {page:WordSection1;} --> 

Вот кусок кода от входа, который включает 2 комментарии, успешно удаляются после запуска моего сценария на нем, а также комментарий, который не удаляется:

<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="Generator" content="Microsoft Word 15 (filtered medium)"> <!--[if !mso]><style>v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} </style><![endif]--><style><!-- /* Font Definitions */ @font-face {font-family:"Cambria Math"; panose-1:2 4 5 3 5 4 6 3 2 4;} @font-face {font-family:Calibri; panose-1:2 15 5 2 2 2 4 3 2 4;} @font-face {font-family:Verdana; panose-1:2 11 6 4 3 5 4 4 2 4;} @font-face {font-family:inherit;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {margin:0in; margin-bottom:.0001pt; font-size:12.0pt; font-family:"Times New Roman",serif;} a:link, span.MsoHyperlink {mso-style-priority:99; color:blue; text-decoration:underline;} a:visited, span.MsoHyperlinkFollowed {mso-style-priority:99; color:purple; text-decoration:underline;} span.EmailStyle17 {mso-style-type:personal-reply; font-family:"Calibri",sans-serif; color:#1F497D;} .MsoChpDefault {mso-style-type:export-only; font-family:"Calibri",sans-serif;} @page WordSection1 {size:8.5in 11.0in; margin:1.0in 1.0in 1.0in 1.0in;} div.WordSection1 {page:WordSection1;} --></style><!--[if gte mso 9]><xml> <o:shapedefaults v:ext="edit" spidmax="1026" /> </xml><![endif]--><!--[if gte mso 9]><xml> <o:shapelayout v:ext="edit"> <o:idmap v:ext="edit" data="1" /> </o:shapelayout></xml><![endif]--> 

Я не уверен, как лучше всего удалять комментарии CSS. Мне не нужно беспокоиться об удалении содержимого комментариев CSS, просто/* * /, так как остальные должны быть разделены с комментарием HTML, вложенным в

+0

Невозможно воспроизвести проблему. В каком месте во входном HTML этот комментарий находится? – alecxe

+0

Извините, я отредактировал свое оригинальное сообщение, чтобы добавить больше кода –

ответ

3

Я решил проблему. Я удалил их с помощью регулярных выражений, и для всех, кому это интересно, вот мой новый код:

from bs4 import BeautifulSoup, Comment 
import re 

input_text = "" 

for line in open('output.txt'): 
    input_text+=line 

#extract all CSS comments 
text = re.sub('\/*', '', input_text) 
text = re.sub('\*/', '', text) 

soup = BeautifulSoup(text) 

#extract all HTML comments 
comments = soup.findAll(text=lambda text:isinstance(text, Comment)) 
[comment.extract() for comment in comments] 

print soup 
Смежные вопросы