我试图从这个表中获取数据: http://www.worldlifeexpectancy.com/cause-of-death/alzheimers-dementia/by-country/ 我要找的元素是这个国家的名字,在这个例子中是芬兰:
<table cellspacing="0" align="center" class="hc_tbl">
<tbody>
<tr>
<td class="hc_name" style="background-color: transparent;">Finland</td>
下面是我使用的代码:
^{pr2}$但是,这会产生一个错误,说明“NoneType”对象没有属性“find”;因此表元素似乎是作为“None”返回的。在
我也读过一些其他的帖子,似乎也有类似的问题,但在这个案例中,所有的修正都没有奏效。在
任何想法都非常感谢
谢谢你
通过在发送请求时检查站点的来源,可以看出站点是动态的。因此,最好使用浏览器操作工具,如
selenium
:输出:
^{pr2}$该表在页源中不可用。它是通过AJAX请求动态加载的。如果您查看Developer tools下的
Network
选项卡,那么AJAX请求将被发送到这个url-http://www.worldlifeexpectancy.com/j/country-cause?cause=95&order=hight。在您可以看到数据以JSON格式提供。在内置的
.json()
函数的帮助下,您可以只使用requests
模块来获取这些数据。在您可以从这个JSON数据中获取所有数据,如排名、国家和费率。在
部分输出:
^{pr2}$另外,请记住,
<tbody>
元素在页面源代码中永远不可用。浏览器将插入它。因此,在抓取表时,不要在find()
函数中使用tbody
。见Why do browsers insert tbody element into table elements?。在相关问题 更多 >
编程相关推荐