首页 > 解决方案 > 从标签中检索内容

问题描述

在我之前的一篇文章中,我能够检索所有 p 标签

import bs4
from urllib.request import  urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url='https://www.centralpark.com/things-to-do/central-park-zoo/polar-bears/'
# opening up connection
uClient = uReq(my_url)
page_html = uClient.read()
# close connection
uClient.close()
page_soup = soup(page_html, features="html.parser")

ps=list(page_soup.find_all('p'))

for s in ps:
    print(s)

我想要的是检索那些 p 标签中的任何内容。前任:

ex1='<p> this is example </p>' -> I want res1 = 'this is example' 
ex2='<p> this is <strong> nice </strong> example </p>' -> I want res2 = 'this is nice example' 
ex3='<p> this is <b> okeyish </b> example </p>' -> I want res3 = 'this is okeyish example'

所有结果(res1,res2,res3)都可以进入列表。

我已经搜索了解决方案,但建议的解决方案仅适用于一种类型的标签示例。我想要的只是检索 p 和 /p 之间的所有内容,无论中间出现哪些其他标签。如果那些其他标签有内容,那些也应该包括在内。

标签: pythonpython-3.xbeautifulsoup

解决方案


ps=page_soup.find_all('p')

results = []
for s in ps:
    #print(s.text)
    results = results.append(s.text)

推荐阅读