【问题标题】:Python AttributeError:'NoneType' object has no attribute getTextPython AttributeError:'NoneType' 对象没有属性 getText
【发布时间】:2020-11-01 03:25:11
【问题描述】:

这是我第一次来这里!我是 python 新手,我收到错误:“'NoneType' 对象没有属性 getText。” 我正在使用 Requests 和 BeautifulSoup 库。它是关于 chess.com,一个国际象棋网站,您可以在其中下载所有数据游戏。我正在学习网络抓取和数据可视化,我的想法是使用我的信息。代码是:


text = page.text

b = BeautifulSoup(text, 'html.parser')

content = b.find('span', attrs={'class': re.compile("archive-games-game-time")})

content.getText().strip()

“massarov”是我在页面中的用户名。我不知道怎么了。谁能帮帮我?????

【问题讨论】:

  • 首先尝试print(content) 看看你得到了什么(那是为了调试)。原因可能是您要查找的内容不存在或找不到
  • b.find 返回的值为 None。在尝试使用getText() 之前,您需要检查if content is not None:。我的猜测是,你的 find 没有找到你要找的东西。
  • 其实我可能已经明白了。您是否也在该页面中登录您的帐户?

标签: python beautifulsoup attributeerror


【解决方案1】:

如果您正在登录,最好使用session,因为它会保留您的 cookie:

session = requests.Session()
session.post(post_link, data=yourdata)

data = session.get(link)

这将使您在更改 url 时保持登录状态(转到网站上的不同页面)。因此,每当需要保留 cookie 时,请使用 session

【讨论】:

  • 感谢Matiiss的回答!,我用类似的方式做了,但我仍然得到同样的错误,可以吗?:import requests from bs4 import BeautifulSoup s = requests.Session() data = {"login":"massarov", "password":"******"} url = "https://www.chess.com/login_and_go?returnUrl=https%3A%2F%2Fwww.chess.com%2F" r = s.post(url, data=data) page = requests.get('https://www.chess.com/games/archive/massarov') text = page.text b = BeautifulSoup(text, 'html.parser') import re content = b.find('span', attrs={'class': re.compile("archive-games-game-time")}) content.getText().strip()
  • @MaximilianoVazquez 我很确定我明确表示你必须通过会话获取数据(在你的情况下是这样的)page = session.get('https://www.chess.com/games/archive/massarov')
  • 谢谢!但它不起作用。这是我正在使用的原始帖子,似乎不需要使用 session/session.post,... [链接] (towardsdatascience.com/…))
  • @MaximilianoVazquez 在这种情况下你的脚本无法找到你要求它找到的东西
猜你喜欢
  • 1970-01-01
  • 2022-01-07
  • 2013-11-06
  • 2021-03-24
  • 2013-04-08
  • 2017-12-28
  • 2017-10-05
  • 2018-03-17
  • 2019-01-10
相关资源
最近更新 更多