Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在使用python的web抓取中,获取标记的内容而不获取其子项的内容_Python_Html_Web Scraping_Beautifulsoup - Fatal编程技术网

在使用python的web抓取中,获取标记的内容而不获取其子项的内容

在使用python的web抓取中,获取标记的内容而不获取其子项的内容,python,html,web-scraping,beautifulsoup,Python,Html,Web Scraping,Beautifulsoup,我正在使用beautifulsoup从报纸网站上抓取数据。我试着把新闻文章储存在列表中。但在文章段落之间有广告位。我想记下段落,但留下广告内容 我曾想过使用一个条件,仅当内容不在该中,但无法找到这样的内容时,才会接收该内容 下面是我正在使用的网页的一个类似示例。这是网页的简化版本,但问题是相同的 <article> <p style="text-align:justify"> <strong> Location </strong>

我正在使用beautifulsoup从报纸网站上抓取数据。我试着把新闻文章储存在列表中。但在文章段落之间有广告位。我想记下段落,但留下广告内容

我曾想过使用一个条件,仅当内容不在该
中,但无法找到这样的内容时,才会接收该内容

下面是我正在使用的网页的一个类似示例。这是网页的简化版本,但问题是相同的

<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>
我想要什么

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的内容。可能这是一个非常容易的问题,但我已经尝试了好几天。

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


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


extract到底做了什么?@Abrahmed它删除了那些标签extract到底做了什么?@Abrahmed它删除了那些标签
Location
News Content 1
News Content 2
Some random Ad 1
News Content 3
News Content 4
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()