python - AttributeError - 网页抓取 - Python - Selenium
问题描述
我需要从网上抓取下表,我无法使用“find_all”功能解决问题。PyCharm 总是说:
AttributeError: 'NoneType' object has no attribute 'find_all'
我不知道出了什么问题。尝试使用 table.find_all("tr") 或 table.find_all('tr') 字符和下一个属性,如 table.find_all("tr", attrs={"class": "table table-export"}) 和下一个选项,没有任何效果。请你能告诉我我做错了什么吗?
桌子:
<div class="table-options">
<table class="table table-export">
<thead>
<tr>
<!-- ngIf: ActuallyPoints && ActuallyPoints.name == 'AXB' --><th ng-if="currentRole && currentRole.name == 'AXB'" class="id check">
<label ng-click="selectAll()"><input disabled="" id="select-all" type="checkbox" ng-model="all" class="valid value-ng">All</label>
</th><!-- end ngIf: currentRole && currentRole.name == 'AXB' -->
<th>AAA</th>
<th>BBB</th>
<th>CCC</th>
</tr>
</thead>
<tbody>
<!-- ngRepeat: x in ErrorStatus --><tr ng-repeat="x in ErrorStatus" class="random-id">
<!-- ngIf: currentRole && currentRole.name == 'AXB' --><td ng-if="currentRole && currentRole.name == 'AXB'" class="random-id">
<input type="checkbox" ng-model="x.checked" ng-change="selectOne(x)" class="valid value-ng">
</td><!-- end ngIf: currentRole && currentRole.name == 'AXB' -->
<td class="pax">111</td>
<td class="pax">222</td>
<td class="pax">333</td>
</td>
</tr><!-- end ngRepeat: x in ErrorStatus -->
</tbody>
</table>
</div>
代码:
import lxml
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = 'xxx'
website = request.urlopen(url).read()
soup = BeautifulSoup(website, "lxml")
table = soup.find("table", attrs={"class": "table table-export"})
rows = table.find_all('tr')
非常感谢。
解决方案
由于没有链接,我将无法提供解决方案,但对错误的解释非常简单:
AttributeError: 'NoneType' object has no attribute 'find_all'
让我们看看您.find_all
在代码中使用的位置:
rows = table.find_all('tr')
考虑到解释器所说的,这段代码实际上看起来像:
rows = None.find_all('tr')
换句话说,您的变量table
等于None
. 因此,您的问题在这里:
table = soup.find("table", attrs={"class": "table table-export"}) # returns None
在人类语言中,您试图在 html 中找到一些表,然后将其存储到 variable table
,但soup.find()
无法使用您提供的指令找到元素,因此返回None
。您没有注意到它并尝试调用None.find_all()
,但None
没有此方法。
这就是您收到此错误的原因。如果您无法共享链接,请自行重新检查此部分,因为它不起作用:
table = soup.find("table", attrs={"class": "table table-export"}) # returns None
UPD:首先,尝试打印变量soup
并检查表是否存在,因为您在浏览器中看到的 html 和您通过请求收到的 html 可能完全不同:
soup = BeautifulSoup(website, "lxml")
print(soup)
推荐阅读
- c++ - 难以理解的 Leetcode 140 解决方案
- sql - 如何使用过滤器字符串过滤日期范围(SQL Server)
- mysql - Reacts JS/SpringBoot 错误:无法在 API 中将字符串转换为长更新方法
- docker - 无法在 /etc/supervisor/conf.d/ docker 文件中复制 .conf
- python - 开发一种迭代算法,该算法返回等距的拼接
- docker - docker-credential-ecr-login 未安装或在 PATH 中不可用(Dockerfile 未使用 docker-compose 构建)
- dart - 您如何将目录的内容保存到 dart 中的变量中?
- c++ - 显示一个没有获得焦点的 Qt 窗口
- python - 我可以将图像作为像素值的熊猫数据框输入到 CNN 中吗?
- flutter - NoSuchMethodError:在 null 上调用了方法“markNeedsBuild”