首页 > 解决方案 > 使用 map 和 lambda 加入 BeautifulSoup Contents

问题描述

我想抓取网页内容并清理格式

from bs4 import BeautifulSoup
import urllib.request
import urllib.parse
import lxml
url='https://en.wikipedia.org/wiki/Deep_learning'
page=urllib.request.urlopen(url)
soup=BeautifulSoup(page,"lxml")
fetched_text=' '.join(map(lambda p: p.text.soup.find_all('p'),soup))

它有如下错误: 在此处输入图像描述

此代码最初是从这样的 youtube 教程中找到的:

fetched_text=' '.join(map(lambda p: p.text.soup.find_all('p')))

但有人抱怨 map() 没有正确使用。 在此处输入图像描述

任何人都可以在这里帮助我吗?

标签: pythonbeautifulsoupurllib

解决方案


也许你使用列表理解更舒服:

fetched_text=' '.join([p.text for p in soup.find_all('p')])

或者你可以用 map 来做,记住 map 等待一个函数和一个迭代:

fetched_text=' '.join(map(lambda p: p.text, soup.find_all('p')))

推荐阅读