首页 > 解决方案 > 错误 'NoneType' 对象没有属性 'find' 有时会导致

问题描述

我正在通过从赛马结果网站中提取数据来学习使用 Python(3.7)和 BS4 进行网络抓取。网址为http://racing.hkjc.com/racing/Info/Meeting/Results/English/Local/20080412/ST/5

这是我的代码的一部分。主要目的是试图从table > tbody > tr > td 中获取数据。表的类是{'class': 'tableBorder trBgBlue tdAlignC number12 draggable'}

import urllib.request
from bs4 import BeautifulSoup

theURL = "http://racing.hkjc.com/racing/Info/Meeting/Results/English/Local/20080412/ST/5"
thePage = urllib.request.urlopen(theURL)
soup = BeautifulSoup(thePage, "html.parser")
table = soup.find('table', {'class': 'tableBorder trBgBlue tdAlignC number12 draggable'})
tBody = table.find('tbody')
for tRows in tBody.find_all('tr'):
   # Get the td.text

有时我可以获取表中的所有数据并写入 csv 文件。但有时会导致以下错误。

Traceback (most recent call last):
  File "K:/fyp/raceRecord.py", line 32, in <module>
    tBody = table.find('tbody')
AttributeError: 'NoneType' object has no attribute 'find'

我知道这个错误会因为table.find('tbody')正在返回而引起None。但是,我不知道为什么有时代码有效但有时无效。是因为页面还在加载table.find('tbody') = None吗?谢谢。

标签: pythonweb-scrapingbeautifulsoup

解决方案


我认为这将解决问题。执行“urllib.request.urlopen”时页面未正确加载。代码正在检查表是否存在。请检查并让我知道。谢谢你。

import urllib.request
from bs4 import BeautifulSoup

theURL = "http://racing.hkjc.com/racing/Info/Meeting/Results/English/Local/20080412/ST/5"
while (True):
    thePage = urllib.request.urlopen(theURL)
    soup = BeautifulSoup(thePage, "html.parser")
    table = soup.find('table', {'class': 'tableBorder trBgBlue tdAlignC number12 draggable'})
    if (table != None):
        tBody = table.find('tbody')
        break

推荐阅读