javascript - 如何从网页中获取唯一的 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 存在。任何帮助,将不胜感激。
谢谢你。
解决方案
有一个
href
属性具有 pdf URL,但会URL
在网页中打开 pdf。所以我
URL
从href
属性中提取 pdf 并从中获取 pdf 名称,然后与https://www.qp.alberta.ca/documents/Acts/
URL 连接。
您可以编写如下代码来获取 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");
输出:
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;
推荐阅读
- python - 按 _id 删除文档不起作用
- java - Java - 如何以 Reader/Processor/Writer 模式优化此文件编写器组件
- php - 重定向路由上的无限循环
- character-encoding - 这是什么编码:
- java - 在 Eclipse EE 中更新 m2e 版本?
- codeigniter - 注册用户 CRUD 操作和其他
- hive - 是否可以在 hive 中更新复杂的数据类型?例如:映射、数组、结构
- visual-studio - 使用 MS VS15 2017 编译 OpenCV 3.4 和 Cuda 9.2
- c++ - C++ 窗口捕获输出与所述窗口的大小不同
- python - 循环 clump_masked 索引