首页 > 解决方案 > AttributeError:“NoneType”对象在 tbody 中没有“find”属性

问题描述

我是 python 领域的新手,并尝试设置一个网络抓取工具。所以我正在试验一些代码。

import requests
import bs4

website = requests.get("https://www.hltv.org/stats/teams")

soup = bs4.BeautifulSoup(website.text, "html.parser")

leaderboard = soup.find("table", {id: "stats-table player-ratings-table"})
tbody = leaderboard.find("tbody")

for tr in tbody.find.all('tr'):
    team = tr.find.all('td')[0].text.strip()
    maps = tr.find.all('td')[1].text.strip()
    kd = tr.find.all('td')[3].text.strip()
    rating = tr.find.all('td')[4].text.strip()

    print(team, maps, kd, rating)

我收到以下错误,有什么帮助吗?我用2.7。

 File "/Users/*****/Python/New Webscraping/WebS.py", line 11, in <module>
    tbody = leaderboard.find("tbody")
AttributeError: 'NoneType' object has no attribute 'find'

Process finished with exit code 1

标签: pythonweb-scrapingattributeerror

解决方案


尝试以下操作以获得所需的输出。我忽略了第一个 tr 通过索引它就像[1:]它里面没有td一样。而且,中没有这样的方法.find.all()BeautifulSoup你可以使用.find_all()or.findAll()代替。

import requests
from bs4 import BeautifulSoup

res = requests.get("https://www.hltv.org/stats/teams")
soup = BeautifulSoup(res.text, "html.parser")
for tr in soup.find("table",class_="player-ratings-table").find_all("tr")[1:]:
    team = tr.find_all('td')[0].text.strip()
    maps = tr.find_all('td')[1].text.strip()
    kd = tr.find_all('td')[3].text.strip()
    rating = tr.find_all('td')[4].text.strip()
    print(team, maps, kd, rating)

推荐阅读