BeautifulSoup4 .replace“ TypeError:'NoneType'对象不可调用”(初学者)

时间:2019-01-31 19:04:38

标签: python beautifulsoup

我收到一条错误消息,提示TypeError: 'NoneType' object is not callable

我相信变量 sphere 是一个字符串(如果打印的话)会输出包含<a href="http://www.google.com/searchbyimage?image_url=https://website/image.png/"><i class="icon-camera"></i><strong>find similar</strong></a>的信息行,但是.replace()会得到一个None值(我认为)

如果为sphere提供了一个字符串值,则它可以正常工作

import requests
import time
from bs4 import BeautifulSoup
url = 'https://example.com/'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'}
page = requests.get(url, headers=headers)
contents = page.content
soup = BeautifulSoup(contents, 'html.parser')


link = soup.find_all('a')
print (link[34]) # prints a line that I need
sphere = link[34]

sphere.replace('<a href=http://www.google.lt/searchbyimage?image_url=', '') # error here

1 个答案:

答案 0 :(得分:0)

在这种情况下,尽管看起来好像sphere是一个字符串,但是如果我们检查type(sphere),我们会看到它是bs4.element.Tag。最简单的解决方案是先将其转换为字符串:

sphere = str(link[34])
sphere.replace('<a href=http://www.google.lt/searchbyimage?image_url=', '') # error here