【问题标题】:Python: AttributeError: 'ResultSet' object has no attribute 'get'Python:AttributeError:'ResultSet'对象没有属性'get'
【发布时间】:2018-03-01 22:10:15
【问题描述】:

当我尝试从网站上抓取一个值并将其放入有效负载请求中时,我收到错误:

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

这是我的代码:

resumeURL='url'
response=self.session.get(resumeURL,headers=headers)
soup=BeautifulSoup(response.content, "html.parser")

product=soup.find_all('input',{'name':'_CsrfToken', 'type':'hidden'})
payload = {
    '_CsrfToken':product.get('value')

当我将find_all 更改为find 时出现错误:

AttributeError: 'NoneType' object has no attribute 'get'

我做错了什么?

【问题讨论】:

  • 正如错误消息所说,productNonesoup.find_all() 在找不到任何匹配元素时返回 None,所以这可能是问题所在。一个简单的print(product) 就足以检验这个假设。
  • _CsrfToken 肯定在页面上。
  • 哎呀,谢谢@Alasdair
  • print(product) 给了我整个代码,我正在寻找 CsrfToken 的值
  • 当我打印(产品)时,我得到:
    我现在如何获取 _CsrfToken 的值并将其放入我的有效负载中?

标签: python beautifulsoup


【解决方案1】:

直接取自美汤documentation

AttributeError: 'ResultSet' object has no attribute 'foo' - 这通常是因为您希望 find_all() 返回单个标记或字符串。但是 find_all() 返回标签和字符串的 list - 一个 ResultSet 对象。您需要遍历列表并查看每个列表的 .foo 。或者,如果你真的只想要一个结果,你需要使用 find() 而不是 find_all()。

因此,如果您想要所有结果 - 而不仅仅是一个 - 您需要遍历所有结果集(例如 product)并查找每个结果集的 .get。 所以像:

for val in product:
  #check the val.get('value') for each member of list
  print val.get('value')

【讨论】:

  • 当我为产品中的产品做: print(data.get('value')) 我得到了值,但是,我现在如何将它添加到有效负载中?
  • 一般来说,更新字典的语法是dict_name[key] = "value",所以你可以做payload[_CsrfToken] = x,其中x是你希望放入@987654329的ResultSet的data.get('value') @
【解决方案2】:

我认为 get 方法应该在 ResultSet 的一个元素中使用(而不是在整个集合中)。我的意思是,你在哪里做:

product.get('value')

尝试:

product[0].get('value')

【讨论】:

  • 这给了我错误:TypeError: 'NoneType' object has no attribute 'getitem'
猜你喜欢
  • 1970-01-01
  • 2016-06-26
  • 2016-11-08
  • 2014-04-26
  • 2021-01-15
  • 2020-03-09
  • 2013-05-14
  • 2011-12-02
相关资源
最近更新 更多