首页 > 解决方案 > 如何从网页中获取唯一的 PDF url?

问题描述

我正在尝试使用 Selenium 获取一些 DOM 元素,并且我正在使用 Java 完成所有这些操作,但是在尝试时出现此错误:

Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

在这一切中我仍然是新手,但我用来检索 DOM 元素的代码是:

 driver.get("https://www.qp.alberta.ca/570.cfm?frm_isbn=9780779808571&search_by=link");
String pagePdfUrl = driver.findElement(By.xpath("//img[@alt='View PDF']//..//parent::a")).getAttribute("href");

我相信错误是它找不到给定的 XPath,尽管这个 xpath 存在。任何帮助,将不胜感激。

谢谢你。

标签: javascriptjavaseleniumweb-scrapingdom

解决方案


  • 有一个href属性具有 pdf URL,但会URL在网页中打开 pdf。

  • 所以我URLhref属性中提取 pdf 并从中获取 pdf 名称,然后与https://www.qp.alberta.ca/documents/Acts/URL 连接。

您可以编写如下代码来获取 pdf URL。

获取PDFURL的代码:

    driver = new ChromeDriver();
    /*I hard coded below URL. You need parameterize based on your requirement.*/
    driver.get("https://www.qp.alberta.ca/570.cfm?frm_isbn=9780779808571&search_by=link");
    String pagePdfUrl = driver.findElement(By.xpath("//img[@alt='View PDF']//..//parent::a")).getAttribute("href");
    System.out.println("Page PDF URL: " + pagePdfUrl);
    String pdfName = StringUtils.substringBetween(pagePdfUrl, "page=", ".cfm&");
    driver.get("https://www.qp.alberta.ca/documents/Acts/" + pdfName + ".pdf");

下载代码PDF

必需的 ChromOptions:

   ChromeOptions options = new ChromeOptions();
   HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
       chromeOptionsMap.put("plugins.plugins_disabled", new String[] { "Chrome PDF Viewer" });
       chromeOptionsMap.put("plugins.always_open_pdf_externally", true);
       chromeOptionsMap.put("download.default_directory", "C:\\Users\\Downloads\\test\\");
       options.setExperimentalOption("prefs", chromeOptionsMap);
       options.addArguments("--headless");
  

访问 PDF:

    driver = new ChromeDriver(options);
    driver.get("https://www.qp.alberta.ca/570.cfm?frm_isbn=9780779808571&search_by=link");
    String pagePdfUrl = driver.findElement(By.xpath("//img[@alt='View PDF']//..//parent::a")).getAttribute("href");
    System.out.println("Page PDF URL: " + pagePdfUrl);
    String pdfName = StringUtils.substringBetween(pagePdfUrl, "page=", ".cfm&");
    System.out.println("Only PDF URL: "+"https://www.qp.alberta.ca/documents/Acts/" + pdfName + ".pdf");
    driver.get("https://www.qp.alberta.ca/documents/Acts/" + pdfName + ".pdf");

输出

Page PDF URL: https://www.qp.alberta.ca/1266.cfm?page=2017ch18_unpr.cfm&leg_type=Acts&isbncln=9780779808571
Only PDF URL: https://www.qp.alberta.ca/documents/Acts/2017ch18_unpr.pdf

导入StringUtils

import org.apache.commons.lang3.StringUtils;

推荐阅读