【问题标题】:BeautifulSoup4 .replace "TypeError: 'NoneType' object is not callable" (Beginner)BeautifulSoup4 .replace "TypeError: 'NoneType' object is not callable" (初学者)
【发布时间】:2019-06-25 07:50:15
【问题描述】:

我收到一条错误消息,上面写着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

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-18
      • 2020-03-09
      • 1970-01-01
      • 2018-03-31
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      相关资源
      最近更新 更多