Python 2.7 AttributeError:'ResultSet'对象没有属性'replace'

时间:2017-11-27 01:03:24

标签: python python-2.7 beautifulsoup urllib

我正在使用BeautifulSoup和urllib制作维基百科网络刮刀。我只是不断得到同样令人讨厌的错误。

我的代码:

from bs4 import BeautifulSoup
import urllib

page = urllib.urlopen("https://en.wikipedia.org/wiki/Donald_Trump").read()
soup = BeautifulSoup(page, "html.parser")
nickname = soup.find_all("span", class_="nickname")
nickname.replace('[<span class="nickname">','')
nickname.replace('</span>]','')
print(nickname)

错误:

AttributeError: 'ResultSet' object has no attribute 'replace'

1 个答案:

答案 0 :(得分:0)

nickname的数据类型为ResultSet,如果要对其执行某些字符串操作,则必须将其转换为字符串。

from bs4 import BeautifulSoup
import urllib

page = urllib.urlopen("https://en.wikipedia.org/wiki/Donald_Trump").read()
soup = BeautifulSoup(page, "html.parser")
nickname = soup.find_all("span", class_="nickname")
nicknameStr = str(nickname)
nicknameStr.replace('[<span class="nickname">','')
nicknameStr.replace('</span>]','')
print(nicknameStr)