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

时间:2018-03-03 11:02:46

标签: python web-scraping beautifulsoup findall

我是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一样)。

1 个答案:

答案 0 :(得分: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