【发布时间】:2020-10-30 09:38:19
【问题描述】:
我正在使用 beautifulsoup 从报纸网站上抓取数据。我正在尝试获取新闻文章并将它们存储在列表中。但是文章段落之间有广告位。我想截取段落但留下广告内容。
我想使用一个条件,仅当内容不在 <div class="ads"> 中但无法找到此类内容时才会获取内容。
这是我正在使用的网页的类似示例。这是网页的简化版本,但问题是一样的。
<article>
<p style="text-align:justify"> <strong> Location </strong> News Content 1 </p>
<p style="text-align:justify"> News Content 2
<div class="ads">
Some random Ad 1
</div>
<br />
News Content 3 <br />
</p>
<p style="text-align:justify"> News Content 4 </p>
</article>
这是我用来从网页中抓取数据的代码 sn-p
soup = bs4.BeautifulSoup(page.content, 'html.parser')
news = soup.find('div',{'class': 'col-md-8 left-container details'})
News_article = news.find_all('div',{'class': 'news-article'})
for fd in News_article:
find1 = fd.findAll("p")
news_body = ""
for i in find1:
news_body += i.getText()
print(news_body)
我想要什么
Location
News Content 1
News Content 2
News Content 3
News Content 4
我得到了什么
Location
News Content 1
News Content 2
Some random Ad 1
News Content 3
News Content 4
我想获取段落或“p”标签的内容,而不获取其中的 div 内容。也许这是一个非常简单的问题,但我尝试了好几天。
【问题讨论】:
标签: python html web-scraping beautifulsoup