我正在尝试使用 Python + Selenium 从标签中获取 href
,但 href
中包含 "JavaScript"
。所以我无法获取目标 URL。
我正在使用 Python 3.7.3
,selenium 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/