Python 3 «NoneType» объект не имеет атрибута «текст» - PullRequest
0 голосов
/ 05 мая 2018
# import libraries
from urllib.request import urlopen
from bs4 import BeautifulSoup

#specify the url
html = 'https://www.bloomberg.com/quote/SPX:IND'

# query the website and return the html to thevariable 'page'
page = urlopen(html)

# parse the html using beautiful soup and store in variable 'soup'
data = BeautifulSoup(page, 'html.parser')

#take out the <div> of name and get its value
name_box = data.find('h1', attrs={'class': 'companyName_99a4824b'})

name = name_box.text.strip() #strip is used to remove starting and trailing
print (name)

# get the index price
price_box = data.find('div', attrs={'class':'priceText_1853e8a5'})
price = price_box.text
print (price)

Я следовал руководству на medium.com здесь и у меня возникли некоторые конфликты из-за недостатка знаний Python и сценариев, но я думаю, что у меня ошибка на

name = name_box.text

потому что текст не определен, и я не уверен, что они хотели бы, чтобы я определил его с помощью библиотеки BeautifulSoup. Любая помощь может быть оценена. Фактическая ошибка будет ниже

 RESTART: C:/Users/Parsons PC/AppData/Local/Programs/Python/Python36-32/projects/Scripts/S&P 500 website scraper/main.py 
Traceback (most recent call last):
  File "C:/Users/Parsons PC/AppData/Local/Programs/Python/Python36-32/projects/Scripts/S&P 500 website scraper/main.py", line 17, in <module>
    name = name_box.text.strip() #strip is used to remove starting and trailing
AttributeError: 'NoneType' object has no attribute 'text'

1 Ответ

0 голосов
/ 05 мая 2018

Веб-сайт https://www.bloomberg.com/quote/SPX:IND не содержит тега <h1> с именем класса companyName_99a4824b. Вот почему вы получаете вышеупомянутую ошибку.

На сайте. Тег <h1> выглядит так,

<h1 class="companyName__99a4824b">S&amp;P 500 Index</h1>

Таким образом, чтобы выбрать его, вы должны изменить имя класса на companyName__99a4824b.

name_box = data.find('h1', attrs={'class': 'companyName__99a4824b'})

Окончательный результат:

# import libraries
from urllib.request import urlopen
from bs4 import BeautifulSoup

#specify the url
html = 'https://www.bloomberg.com/quote/SPX:IND'

# query the website and return the html to thevariable 'page'
page = urlopen(html)

# parse the html using beautiful soup and store in variable 'soup'
data = BeautifulSoup(page, 'html.parser')

#take out the <div> of name and get its value
name_box = data.find('h1', attrs={'class': 'companyName__99a4824b'}) #edited companyName_99a4824b -> companyName__99a4824b

name = name_box.text.strip() #strip is used to remove starting and trailing
print (name)

# get the index price
price_box = data.find('div', attrs={'class':'priceText__1853e8a5'}) #edited priceText_1853e8a5 -> priceText__1853e8a5
price = price_box.text
print (price)

Было бы лучше, если бы вы также могли обработать это исключение для будущих изменений имени класса.

...