首页 > 解决方案 > 如何在 AngularJS 网站上使用 Python 中的 Selenium 迭代和保存动态表中的信息

问题描述

我正在尝试从使用 AngularJS 的网站上的动态表中抓取数据。我正在使用 Selenium 来抓取网站。

目前,我的问题是我无法识别动态表,因为没有标签。此外,行的 id 还具有字符串形式的动态名称,这使事情变得更加复杂。任何帮助表示赞赏。

我尝试通过 ID/XPATH 搜索并将它们添加到元素列表中。没有成功。

我想要的信息包含在一个使用多个参数动态生成的海量表中(收集日期):

<tctable id="tweb_EPVisitNumber_List_1">

有多行,包含多个其他参数。下面是我感兴趣的一个小专栏的一个例子。我想从生成的表中的所有元素中获取所有日期。

<tccol layout-xs="column" class="layout-xs-column">
<div>
<span id="web_EPVisitNumber_List_1-row-0-item-CollectionDate-label" class="componentTableItemLabel hide-gt-xs ng-binding ng-scope">Collection Date
</span>
<span class="componentTableItem ng-scope">
<span id="web_EPVisitNumber_List_1-row-0-item-CollectionDate" class="ng-binding">17/01/2019
</span>
</span>
</div>
</tccol>

随着表格的进行,ID 将变为动态字符串,例如,其他列/行中的下一个元素将是:

id="web_EPVisitNumber_List_1-row-1-item-CollectionDate" 
id="web_EPVisitNumber_List_1-row-2-item-CollectionDate"
id="web_EPVisitNumber_List_1-row-3-item-CollectionDate"

等等

我的问题是我首先无法在较大的表中找到特定元素,并且随着字符串动态变化,我也无法遍历它。

标签: pythonangularjsseleniumxpathwebdriverwait

解决方案


您必须找到元素的一些共同属性,并基于它构建定位器。例如,在给定的示例中,所有有趣span的 s 在其 ID 中都有“CollectionDate”,但没有“-label”(列标题有它)。
所以一个带有它的xpath将是:

//span[contains(@id, "CollectionDate") and not contains(@id, "-label")]

另一个观察 - 所有“有趣”的都是spans 在 adiv中,它在 atccol中,具有id; 除了第一个,它是列标题:

//tccol/div/span[@id and not position()=1]

推荐阅读