簡體   English   中英

如何從web頁面獲取唯一的PDF url?

[英]How to get the only PDF url from web page?

我正在嘗試使用 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 存在。 任何幫助,將不勝感激。

謝謝你。

  • 有一個href屬性具有 pdf URL 但URL在網頁中打開 pdf。

  • 因此,我從href屬性中提取了 pdf URL ,並從中提取了 pdf 名稱,然后將其與https://www.qp.alberta.ca/documents/Acts/連接起來。

您可以編寫如下代碼來獲取 pdf URL。

獲取PDF URL 的代碼

    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");

OutPut :

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM