python - 错误 '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
吗?谢谢。
解决方案
我认为这将解决问题。执行“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
推荐阅读
- c# - 如何在Unity3D中查找列表中的3个元素是否相同
- python-3.x - 使用解析选择器从动态 Web 表中抓取数据
- python - 如何使用文本相似性删除 pandas 数据框中的相似(不重复)行?
- amazon-web-services - 未发送消息正文中带有链接的 AWS SMS
- python - 为特定列值查找一列的唯一值
- arangodb - 使用 ArangoDB,具有 x 个边定义的 1 个命名图与具有 1 个边定义的 x 个命名图之间的实际区别是什么?
- python - Mac M1 无法安装 PyAudio / 尝试了 StackOverflow 中建议的所有答案
- c# - 握手 - Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerProvider
- google-cloud-platform - 使用数据更新 GCS 中的 AVRO 文件
- verilog - 为什么输出处于未知状态?