AttributeError-网络抓取-Python-硒

时间:2020-05-18 13:13:15

标签: python selenium web-scraping beautifulsoup attributeerror

我需要从网上抓取下表,但无法使用“ 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 &amp;&amp; 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 &amp;&amp; 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')

非常感谢。

1 个答案:

答案 0 :(得分:1)

由于没有链接,我将无法提供解决方案,但是对错误的解释非常简单:

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中查找某个表,然后将其存储到变量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)
相关问题