【问题标题】:Take the contents of a tag without taking the contents of its child in web scraping using python使用 python 在网络抓取中获取标签的内容而不获取其子项的内容
【发布时间】: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


    【解决方案1】:

    您可以使用.extract() 删除不需要的标签:

    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'})
    ads = soup.find_all('div',class_='ads')
    for x in ads: 
        x.extract()
    

    【讨论】:

    • extract到底是做什么的?
    • @AbrarAhmed 它删除了这些标签
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    相关资源
    最近更新 更多