使用beautifulsoup从结果包中删除特定内容

2024-04-20 00:50:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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给我文本的代码

    <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,如果它存在,则忽略它(如果它不存在)。我该怎么做


Tags: thebrdivlinkdescclassbsespan
2条回答

您可以使用^{}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

只需对最后一行进行一些更改并添加re模块

...
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> 

相关问题 更多 >