如何在Python中抓取时同时打印段落和标题?

问题描述 投票:0回答:1

我是python的初学者。我目前正在使用Beautifulsoup来抓一个网站。

str='' #my_url
source = urllib.request.urlopen(str);
soup = bs.BeautifulSoup(source,'lxml');
match=soup.find('article',class_='xyz');
for paragraph in match.find_all('p'):
    str+=paragraph.text+"\n"

我的标签结构 -

<article class="xyz" >
<h4>dr</h4>
<p>efkl</p>
<h4>dr</h4>
<p>efkl</p>
<h4>dr</h4>
<p>efkl</p>
<h4>dr</h4>
<p>efkl</p>         
</article>

我得到这样的输出(因为我能够提取段落) -

 efkl
 efkl
 efkl
 efkl

我想要的输出(我想要标题和段落) -

 dr
 efkl
 dr
 efkl
 dr
 efkl
 dr
 efkl     

我希望我的输出还包含标题和段落。如何修改代码,使其包含段落之前的标题(就像在原始HTML中一样)。

python web-scraping beautifulsoup findall
1个回答
2
投票

你可以用不同的方法剥掉同一个苹果来达到目的。以下是其中一些:

使用.find_next()

from bs4 import BeautifulSoup

content="""
<article class="xyz" >
<h4>dr</h4>
<p>efkl</p>
<h4>dr</h4>
<p>efkl</p>
<h4>dr</h4>
<p>efkl</p>
<h4>dr</h4>
<p>efkl</p>         
</article>
"""
soup = BeautifulSoup(content,"lxml")

for items in soup.find_all(class_="xyz"):
    data = '\n'.join(['\n'.join([item.text,item.find_next("p").text]) for item in items.find_all("h4")])
    print(data)

使用.find_previous_sibling()

for items in soup.find_all(class_="xyz"):
    data = '\n'.join(['\n'.join([item.find_previous_sibling("h4").text,item.text]) for item in items.find_all("p")])
    print(data)

常用方法:列表中使用的多个标签:

for items in soup.find_all(class_="xyz"):
    data = '\n'.join([item.text for item in items.find_all(["h4","p"])])
    print(data)

所有这三种方法都产生相同的结果:

dr
efkl
dr
efkl
dr
efkl
dr
efkl
© www.soinside.com 2019 - 2024. All rights reserved.