Use Selenium to click on a file link, store the html into a variable and download a specific filename with certainy text

Viewed 192

Need assistance to complete the rest tasks:

  1. Click and open the link under "SUMMARY"
  2. Copy the new html link to a variable for future use.
  3. Download the pdf into a folder

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Firefox(executable_path = "C:\Program Files\Mozilla Firefox\geckodriver.exe")
driver.maximize_window()
driver.implicitly_wait(30)
driver.get("https://www1.hkexnews.hk/search/titlesearch.xhtml")
wait = WebDriverWait(driver, 20)
StockList = ['02192']
wait.until(EC.element_to_be_clickable((By.ID, "searchStockCode"))).send_keys(StockList[0])


wait.until(EC.element_to_be_clickable((By.ID, "searchTitle"))).send_keys( "Announcement of Offer Price and Allotment Results" )


ele = wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='slimScrollDiv']/descendant::tbody/tr[1]")))
ActionChains(driver).move_to_element(ele).click().perform()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[class*='applyFilters']"))).click()

driver.find_element_by_link_text("Announcement of Offer Price and Allotment Results").click()

1 Answers

You can use the below xpath :

a[rel='noopener noreferrer']

to click on link.

new_link_element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[rel='noopener noreferrer']")))
var_new_link = new_link_element.get_attribute('href')

in case you wanna click on it, you can do it like :

new_link_element.click()

Udpate :

once you click on Announcement of Offer Price and Allotment Results, a new tab will be opened up,

so next you have to switch the driver focus like this :

driver.switch_to.window(driver.window_handles[1])
wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "SUMMARY"))).click()
Related