javascript - 如何使用 Python 从包含 JavaScript 的 <a> 标签获取 href?

标签 javascript python selenium web-scraping

我正在尝试使用 Python + Selenium 从标签中获取 href,但 href 中包含 "JavaScript"。所以我无法获取目标 URL。

我正在使用 Python 3.7.3selenium 3.141.0

HTML:

<a href="javascript:GoPDF('FS1546')" style="TEXT-DECORATION: Underline">Aberdeen Standard Wholesale Australian Fixed Income</a>

代码:

from selenium import webdriver
driver = webdriver.Chrome("chromedriver.exe")
driver.get("http://www.colonialfirststate.com.au/Price_performance/performanceNPrice.aspx?menutabtype=performance&CompanyCode=001&Public=1&MainGroup=IF&BrandName=FC&ProductIDs=91&Product=FirstChoice+Wholesale+Investments&ACCodes=&ACText=&SearchType=Performance&Multi=False&Hedge=False&IvstType=Investment+products&IvstGroup=&APIR=&FundIDs=&FundName=&FundNames=&SearchProdIDs=&Redirect=1")
print(driver.find_elements_by_xpath("tbody/tr[5]/td[1]/a")

我需要的是目标 URL 作为:

https://www3.colonialfirststate.com.au/content/dam/prospects/fs/1/5/fs1546.pdf?3

但它给了我:

javascript:GoPDF('FS2311')

最佳答案

我检查了弹出窗口中的 PDF 网址,并了解了他们是如何生成网址的。

他们使用文件名(例如 FS2065)生成 PDF URL。

PDF 的 url 看起来像这样, https://www3.colonialfirststate.com.au/content/dam/prospects/fs/2/0/fs2065.pdf?3

对于这部分之前的所有 PDF,它具有相同的路径

https://www3.colonialfirststate.com.au/content/dam/prospects/

在那部分之后,我们有一个使用 fileID 生成的路径,

fs/2/0/fs2065.pdf?3
 | | |     |     ||
 | | |     |     ++--- Not needed (But you can keep if you want)
 | | |     |
 | | |     +---- File Name
 | | +---------- 4th character in the file name 
 | +------------ 3rd character in the file name 
 +-------------- First two characters in the file name 

我们可以使用它作为解决方法来获取确切的 url。

url = "javascript:GoPDF('FS2311')" # javascript URL  

pdfFileId = url[18:-2].lower() # extracts the file name from the Javascript URL

pdfBaseUrl = "https://www3.colonialfirststate.com.au/content/dam/prospects/%s/%s/%s/%s.pdf?3"%(pdfFileId[:2],pdfFileId[2],pdfFileId[3],pdfFileId) 

print(pdfBaseUrl)
# prints https://www3.colonialfirststate.com.au/content/dam/prospects/fs/2/3/fs2311.pdf?3

查看实际效果 here .

关于javascript - 如何使用 Python 从包含 JavaScript 的 <a> 标签获取 href?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57883598/

相关文章:

javascript - 隐藏的溢出在 iPad 中不起作用

javascript - 如何用href定位div加载

javascript - JavaScript 中鼠标移出时恢复旧版 CSS

Python通过islice循环读取20条记录

python - 我正在创建这个基于人工智能的战术脚趾应用程序

java - sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 通过 Selenium 和 Java 使用 findElement(By.className())

selenium - 如何使用 Java 在 Selenium Webdriver 中使用 clickandwait?

javascript - jQuery序列化并插入mysql

python - HTML 不反射(reflect) Beautiful Soup 浏览器中的网页内容

python - 禁用日期选择器上的 Selenium 输入日期