Вопрос по парсингу

В html коде страницы есть:

В парсере в список контента я добавляю item таким образом:

hero = item.find('td', class_='cell-xlarge').get('data-value')

На выходе ошибка:

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

Что нужно исправить, как правильно спарсить значение data-value?
Полный код тут


Ответы (1 шт):

Автор решения: Jack_oS

Вы получаете AttributeError: 'NoneType' object has no attribute 'get' из-за того, что items = soup.find_all('tr') находит все строки, в заголовке таблицы в том числе, а в нем нет 'td' class_='cell-xlarge'. Можно или взять только элементы из тела таблицы:

items = soup.find('tbody').find_all('td', class_='cell-xlarge')

for item in items:
    print(item.text)

или оставить ваш вариант, но сделать срез без первого элеманта:

for item in items[1:]:
    print(item.find('td', class_='cell-xlarge').text)

Оба варианта выводят имена:

Pudge
Juggernaut
Lion
...
Elder Titan
Visage
Chen

Если есть необходимость вытащить все значимые данные, можно собрать все строки в tbody таблицы и перебирать в них td, примерно так:

rows = soup.find('tbody').find_all('tr')

for row in rows:
    tds = row.find_all('td')

Итоговый код:

import requests
from bs4 import BeautifulSoup

url = 'https://www.dotabuff.com/heroes/played?date=month'
headers = {
    'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
}

r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')

rows = soup.find('tbody').find_all('tr')

for row in rows:
    tds = row.find_all('td')

    name = tds[1].text
    matches = tds[2].text.replace(',', '')
    pick_rate = tds[3].text
    win_rate = tds[4].text
    ratio = tds[5].text

    print(f'{name:20} matches: {matches}, pick: {pick_rate}, win: {win_rate}, ratio: {ratio}')

будет выводить на печать:

Pudge                matches: 4621108, pick: 25.76%, win: 50.54%, ratio: 2.25
Juggernaut           matches: 3875575, pick: 21.60%, win: 53.37%, ratio: 3.24
Lion                 matches: 3863652, pick: 21.53%, win: 50.25%, ratio: 2.05
...
Elder Titan          matches: 271008, pick: 1.51%, win: 49.75%, ratio: 2.45
Visage               matches: 231091, pick: 1.29%, win: 51.09%, ratio: 3.16
Chen                 matches: 100342, pick: 0.56%, win: 46.51%, ratio: 2.36
→ Ссылка