python - 网络抓取最常见的名字
问题描述
我需要在网页上抓取网页并找到五个最常见的名字。预期的输出应该看起来像
[
('Anna Pavlovna', 7),
('the prince', 7),
('the Empress', 3),
('Theprince', 3),
('Prince Vasili', 2),
]
我的代码确实计算了最常见的名称,但输出看起来像这样:
[(<span class="green">Anna Pavlovna</span>, 7),
(<span class="green">the prince</span>, 7),
(<span class="green">the Empress</span>, 3),
(<span class="green">The prince</span>, 3),
(<span class="green">Prince Vasili</span>, 2)]
我该怎么做才能使我的输出看起来像示例输出?
import nltk
from urllib.request import urlopen
from bs4 import BeautifulSoup
html=urlopen('http://www.pythonscraping.com/pages/warandpeace.html')
soup=BeautifulSoup(html,'html.parser')
nameList = soup.findAll("span", {"class":"green"}) # may use bsObj.find_all()
fdist1 = nltk.FreqDist(nameList)
fdist1.most_common(5)
解决方案
该页面显示错误 502 Bad Gateway,但我想我知道您的问题是什么。当您使用 findAll 时,它会为您提供 bs4 元素而不是字符串。因此,您需要使用类似 obj.get_text() 的方式将其转换为字符串。 见文档
items = soup.findAll("span", {"class": "green"})
texts = [item.get_text() for item in items]
# Now you have the texts of the span elements
顺便说一句,您的代码示例不正确,因为不会定义 bsObj。
推荐阅读
- javascript - OdooV14 - 在向下滚动时显示标题徽标
- c - 在 ARM macOS 上,当显式 raise()-ing 信号时,堆栈上的一些返回地址会出现乱码
- c - 如何更准确地衡量上下文切换的成本
- javascript - 断点在第一行以外不可用
- c# - 如何动态创建表达式
从一个表达式 ? - google-chrome - AdBlock 认为我的 websocket 请求是广告
- java - 构建错误 Jenkins:org.openqa.selenium.WebDriverException:等待驱动程序服务器启动超时
- php - Laravel 和 Vuejs 的跨域资源共享 (CORS)
- macos - 在网站上下载阻止检查元素的视频
- jenkins-pipeline - 使用 jenkins 管道的 Liquibase 实现