Web Scraper:为什么会出现AttributeError:'NoneType'对象没有属性'text'?

时间:2019-08-28 03:57:03

标签: python

我正在制作我的第一个Web刮板,该刮板应该从Bloomberg.com返回S&P 500索引,但是当我尝试运行它时,出现以下错误消息:AttributeError:'NoneType'对象没有属性'text'

我用作参考的代码(来自https://www.freecodecamp.org/news/how-to-scrape-websites-with-python-and-beautifulsoup-5946935d93fe/)使用了urllib2,据我了解,该库已拆分为多个库。所以我不确定这是否是问题所在?

  from urllib.request import urlopen
  from bs4 import BeautifulSoup

  url = 'https://www.bloomberg.com/quote/SPX:IND'

  htmlpage = urlopen(url)

  soup = BeautifulSoup(htmlpage, 'html.parser')

  name_box = soup.find('h1', attrs={'class':'name'})

  name = name_box.text.strip(0)
  print(name)

  price_box = soup.find('div', attrs={'class':'price'})
  price = price_box.text
  print(price)

它应该从Bloomberg.com返回标普500指数。

1 个答案:

答案 0 :(得分:0)

可能找不到您要查找的元素。 您可以通过评论来检查

$(document).ready(function() {
  // extract to reusable function
  function onload () {
    alert('loaded');
  }
  setTimeout(() => {

    // create image
    const $img = $('<img src="https://via.placeholder.com/150" />')

    // attach load event
    $img.on('load', onload)

    $('#test').append($img);
  }, 1000);
});

并验证name = name_box.text.strip(0) price = price_box.text name的值

还要确保检查price中的HTML,以确保请求成功并且所需的元素可用。