【问题标题】:Iterate through all links of a website using Selenium使用 Selenium 遍历网站的所有链接
【发布时间】:2017-11-07 14:28:00
【问题描述】:

我是 Selenium 的新手,我想从网站下载所有 pdfppt(x)doc(x) 文件。我已经编写了以下代码。但我很困惑如何获取内部链接:

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class WebScraper {

    String loginPage = "https://blablah/login";
    static String userName = "11";
    static String password = "11";
   static String mainPage = "https://blahblah";

    public WebDriver driver = new FirefoxDriver();
    ArrayList<String> visitedLinks = new ArrayList<>();

    public static void main(String[] args) throws IOException {

        System.setProperty("webdriver.gecko.driver", "E:\\geckodriver.exe");

        WebScraper webSrcaper = new WebScraper();
        webSrcaper.openTestSite();
        webSrcaper.login(userName, password);

        webSrcaper.getText(mainPage);
        webSrcaper.saveScreenshot();
        webSrcaper.closeBrowser();
    }

        /**
     * Open the test website.
     */
    public void openTestSite() {

        driver.navigate().to(loginPage);
    }

    /**
     * @param username
     * @param Password Logins into the website, by entering provided username and password
     */
    public void login(String username, String Password) {

        WebElement userName_editbox = driver.findElement(By.id("IDToken1"));
        WebElement password_editbox = driver.findElement(By.id("IDToken2"));
        WebElement submit_button = driver.findElement(By.name("Login.Submit"));

        userName_editbox.sendKeys(username);
        password_editbox.sendKeys(Password);
        submit_button.click();

    }

    /**
     * grabs the status text and saves that into status.txt file
     *
     * @throws IOException
     */
    public void getText(String website) throws IOException {

        driver.navigate().to(website);

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        List<WebElement> allLinks = driver.findElements(By.tagName("a"));

        System.out.println("Total no of links Available: " + allLinks.size());

        for (int i = 0; i < allLinks.size(); i++) {

            String fileAddress = allLinks.get(i).getAttribute("href");

            System.out.println(allLinks.get(i).getAttribute("href"));
            if (fileAddress.contains("download")) {
                driver.get(fileAddress);
            } else {
//                getText(allLinks.get(i).getAttribute("href"));
            }
        }
        
    }

    /**
     * Saves the screenshot
     *
     * @throws IOException
     */
    public void saveScreenshot() throws IOException {
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File("screenshot.png"));
    }

    public void closeBrowser() {
        driver.close();
    }
    
}

我有一个 if 子句,用于检查当前链接是否为可下载文件(地址包含“下载”一词)。如果是,我会得到它,如果不是,怎么办?那部分是我的问题。我试图实现一个递归函数来检索嵌套链接并重复嵌套链接的步骤,但没有成功。

同时,在输入https://blahblah 时找到的第一个链接是https://blahblah/#,它与https://blahblah 指向同一页面。它也可能导致问题,但目前,我陷入了另一个问题,即递归函数的实现。你能帮帮我吗?

【问题讨论】:

  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。避免一次问多个不同的问题。请参阅How to Ask 页面以获得澄清此问题的帮助。
  • @DebanjanB 抱歉,我没有问过多个问题。我的问题很简单直接:如何使用 Selenium 遍历网站的所有链接?我不明白您在我的帖子中看到的其他问题。你能解释一下吗?
  • @user1419243 只是尝试删除else 语句,所以只需给for (int i = 0; i &lt; allLinks.size(); i++) { String fileAddress = allLinks.get(i).getAttribute("href"); System.out.println(allLinks.get(i).getAttribute("href")); if (fileAddress.contains("download")) { driver.get(fileAddress); } }
  • @DebanjanB 再次抱歉,我认为您还没有阅读我的代码。我已经下载了 pdf 文件,并且在您复制的文本中,我只是在“解释”我的代码。我什么都没问。
  • @user1207289 感谢您的回答。这种方法的问题是它试图在第一页上“仅”下载文件,而不是在内部链接中搜索。而且我实际上在主页中没有任何文件。所以,我需要爬得更深。

标签: java selenium selenium-webdriver web-crawler depth-first-search


【解决方案1】:

您离您不远了,但要回答您的问题,将所有链接抓取到元素列表中,迭代并单击(并等待)。使用 C# 类似的东西;

       IList<IWebElement> listOfLinks = _driver.FindElements(By.XPath("//a"));
        foreach (var link in listOfLinks)
        {
            if(link.GetAttribute("href").Contains("download"))
            {
            link.Click();
            WaitForSecs(); //Thread.Sleep(1000)
            }
        }

JAVA

    List<WebElement> listOfLinks = webDriver.findElements(By.xpath("//a"));
    for (WebElement link :listOfLinks ) {

        if(link.getAttribute("href").contains("download"))
        {
            link.click();
            //WaitForSecs(); //Thread.Sleep(1000)
        }
    }

【讨论】:

  • OP 要求使用 Java
【解决方案2】:

如果您想深度优先搜索,一个选项是在您的 java 代码中嵌入 groovy。当 httpBuilder 解析时,它会提供类似 xml 的文档,然后您可以在 groovy 中使用 gpath 尽可能深入地遍历。您的test.groovy 如下所示

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7' )

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.JSON
import groovy.json.*
import org.cyberneko.html.parsers.SAXParser
import groovy.util.XmlSlurper
import groovy.json.JsonSlurper

urlValue="http://yoururl.com"

def http = new HTTPBuilder(urlValue) 

//parses page and provide xml tree , it even includes malformed html 
def parsedText = http.get([:])

// number of a tags. "**" will parse depth-first
aCount= parsedText."**".findAll {it.name()=='a'}.size()

然后你只需从 java 中调用test.groovy,例如this

 static void runWithGroovyShell() throws Exception {
    new GroovyShell().parse( new File( "test.groovy" ) ).invokeMethod( "hello_world", null ) ;
  }

More info 用 groovy 解析 html

补充: 当您在 Java 中评估 groovy 时,要通过 groovy 绑定访问 Java 环境中的 groovy 变量,请查看here

【讨论】:

    猜你喜欢
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 2011-08-28
    相关资源
    最近更新 更多