The href
attribute contains a URL for the PDF, but it opens within the webpage.
To extract the PDF URL from the href
attribute and get the PDF name, I concatenated it with the
https://www.qp.alberta.ca/documents/Acts/
URL.
Below is the code to retrieve the PDF URL:
Code to Retrieve PDF
URL:
driver = new ChromeDriver();
/*The URL below is hardcoded, you need to parameterize it as per your requirements.*/
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");
Code to Download PDF
:
Required 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");
Accessing 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
Import for StringUtils
:
import org.apache.commons.lang3.StringUtils;