使用SeleniumDriver从多个跨度中提取数据

时间:2017-03-27 22:44:36

标签: python selenium-webdriver

所以我有多个网页,其主要部分基本上是一堆<span>标签。其中id的{​​{1}}是随机的。

基本页面结构如下:

span

id始终是随机的,span的标题始终是整数。 (第一页增加1-128,第二页增加129到256.等等。)

我想要做的是拉出范围的<pre> <span id = "abcdf"> <a href="">x</a> <span title="1"> <a href="">random text</a> <a href="">random text</a> </span> ... Repeat ... <span id = "awfaf"> <a href="">x</a> <span title="127"> <a href="">random text</a> <a href="">random text</a> </span> </pre> ,然后是每页第二个和第三个id中的两列/文字。

我不确定如何以可重复的方式进行此操作,只需要了解逻辑,即在浏览页面时要拉出哪些元素。

1 个答案:

答案 0 :(得分:0)

以下是使用Java获取所需数据的方法之一:

List<String> idList = new ArrayList<String>();
        List<String> textList1 = new ArrayList<String>();
        List<String> textList2 = new ArrayList<String>();
        int i=1;
        while (driver.findElements(By.xpath("//pre/span[" + i + "]")).size() != 0) {

            idList.add(driver.findElement(By.xpath("//pre/span[" + i + "]")).getAttribute("id"));
            textList1.add(driver.findElement(By.xpath("//pre/span[" + i + "]/a[2]")).getText());
            textList2.add(driver.findElement(By.xpath("//pre/span[" + i + "]/a[3]")).getText());
            i++;
        }

可以为每个页面执行上面的代码。