2015-09-09 1 views
1
def get_description(link): 
    redditFile = urllib2.urlopen(link) 
    redditHtml = redditFile.read() 
    redditFile.close() 
    soup = BeautifulSoup(redditHtml) 
    desc = soup.find('div', attrs={'class': 'op_gd14 FL'}).text 
    return desc 

Это код, который дает мне текст из этого HTMLУдаление частности содержания из результатов parces с использованием BeautifulSoup

<div class="op_gd14 FL"> 
    <p><span class="bigT">P</span>restige Estates Projects Ltd has informed BSE that the 18th Annual General Meeting (AGM) of the Company will be held on September 30, 2015.Source : BSE<br><br> 
<a href="../../company-notices/nestleindia/notices/PEP02">Read all announcements in Prestige Estate</a> </p><p>            </p> 

</div> 

Этот результат хорошо для меня, я просто хочу, чтобы исключить содержание

<a href="../../company-notices/nestleindia/notices/PEP02">Read all announcements in Prestige Estate</a>

от результата, то есть desc в моем скрипте, если он присутствует и игнорируется, если его нет. Как я могу это сделать?

ответ

2

Вы можете использовать extract() для удаления ненужных тегов из find() результата:

descItem = soup.find('div', attrs={'class': 'op_gd14 FL'}) # get the DIV 
[s.extract() for s in descItem('a')]      # remove <a> tags 
return descItem.get_text()         # return the text 
1

Просто внести некоторые изменения в последнюю строку и добавить модуль повторно

... 
return re.sub(r'<a(.*)</a>','',desc) 

Выход:

'<div class="op_gd14 FL">\n <p><span class="bigT">P</span>restige Estates Projects Ltd has informed BSE that the 18th Annual General Meeting (AGM) of the Company will be held on September 30, 2015.Source : BSE<br><br> \n </p><p> 
+0

спасибо, но все же мне нужно изменение, я думаю, потому что не было бы ' 'in' desc' – cyclic

+0

Изменения не требуются, если r '' == False он просто проходит, так как это – mmachine

+0

нет, потому что 'desc' не будет содержать html. его единственный текстовый контент – cyclic

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