把所有的p元素合并成一个字符串?

2024-04-19 11:02:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前使用以下Python代码摘录获取网页的所有元素:

def scraping(url, html):
    data = {}
    soup = BeautifulSoup(html,"lxml")

    data["news"] = []

    page = soup.find("div", {"class":"container_news"}).findAll('p')
    page_text = ''

    for p in page:
        page_text += ''.join(p.findAll(text = True))
        data["news"].append(page_text)
    print(page_text)

    return data

但是,page_text的输出如下所示:

"['New news on the internet. ', 'Here is some text. ', ""Here is some other."", ""And then there are other variations \n\nLooks like there are some non-text elements. \n\xa0""]" ...

有没有可能让内容更清晰,并将列表合并成一个字符串?BeautifulSoup解决方案将优先于regex变体。你知道吗

谢谢你!你知道吗


Tags: 代码textdatahereishtmlpagesome
1条回答
网友
1楼 · 发布于 2024-04-19 11:02:21

我不确定保持data["news"]的重要性,但这可以用一行代码来完成:

page_text = ' '.join(e.text for p in page for e in p.findAll(text=True))

您可以使用任何您想要的字符串作为分隔符,而不是' '。你知道吗

否则

page_text = []

for p in page:
    page_text.extend(e.text for e in p.findAll(text=True))
    data["news"].append(page_text)

print(' '.join(page_text))

相关问题 更多 >