[英]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.