首页 > 解决方案 > 网络抓取最常见的名字

问题描述

我需要在网页上抓取网页并找到五个最常见的名字。预期的输出应该看起来像

[
    ('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)

标签: pythonweb-scrapingbeautifulsoupnltk

解决方案


该页面显示错误 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。


推荐阅读