2015-12-18 4 views
0

Я хочу получить содержимое div с классом «gt-read», и в div есть еще один div, который имеет другой класс. Ниже приведен код, фрагмент скрипта:
Получите содержимое div в div с помощью BeautifulSoup?

Сценарии:

data = """ 
    <div class='gt-read'> 
     <!-- no need --> 
     <!-- some no need --> 

     <b>Bold text</b> - some text here <br/> 
     lorem ipsum here <br/> 
     <strong> Author Name</strong> 

     <div class='some-class'> 
      <script> 
       #... 
       Js script here 
       #... 
      </script> 
     </div> 
    </div> 
    """ 
soup = BeautifulSoup(data, 'lxml') 
get_class = soup.find("div", {"class" : "detail_text"}) 
print 'notices', notices.get_text() 
print 'notices', notices 

и я хочу результаты, как это:

<b>Bold text</b> - some text here <br/> 
lorem ipsum here <br/> 
<strong> Author Name</strong> 

Пожалуйста, помогите.

ответ

2

Следующие должны показать то, что вам нужно:

from bs4 import BeautifulSoup, Comment 

data = """ 
    <div class='gt-read'> 
     <!-- no need --> 
     <!-- some no need --> 

     <b>Bold text</b> - some text here <br/> 
     lorem ipsum here <br/> 
     <strong> Author Name</strong> 

     <div class='some-class'> 
      <script> 
       #... 
       Js script here 
       #... 
      </script> 
     </div> 
    </div> 
    """ 
soup = BeautifulSoup(data, 'lxml') 
get_class = soup.find("div", {"class" : "gt-read"}) 
comments = get_class.find_all(text=lambda text:isinstance(text, Comment)) 
[comment.extract() for comment in comments] 

get_class.find("div").extract() 
text = get_class.encode_contents().strip() 

print text 

Давать вам следующий вывод:

<b>Bold text</b> - some text here <br/> 
     lorem ipsum here <br/> 
<strong> Author Name</strong> 

Это получает gt-read класс, извлекает все комментарии и Div тег, и возвращает остальные разметки.

+0

Это работа из моего дела, спасибо. это очень полезно! –

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