英文:
How to find and click on an excel file, given that the file name changes?
问题
> link = browser.find_element_by_css_selector('[href^="Reports/DC_REG_"]')
>
> link.click()
英文:
<a id="hlExcel" href="Reports\DC_REG_638123088090882623.xls" target="_blank"><img src="Images/Excel.gif" alt="Click to view a Excel version"></a>
How do I find and click on this excel file that I have to download everyday, given that the file name changes every day. I have tried this:-
> link = browser.find_element_by_css_selector('["href="Reports"]')
>
> link.click()
I am using python Selenium
答案1
得分: 1
给定的HTML代码如下:
<a id="hlExcel" href="Reports\DC_REG_638123088090882623.xls" target="_blank">
<img src="Images/Excel.gif" alt="Click to view a Excel version">
</a>
要点击这个可点击的元素,尽管文件名每天都会更改,理想情况下,您需要使用WebDriverWait来等待元素变为可点击状态,您可以使用以下任何一种定位策略:
- 使用CSS选择器:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a#hlExcel > img[alt='Click to view a Excel version']"))).click()
- 使用XPath:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@id='hlExcel']/img[@alt='Click to view a Excel version']"))).click()
- 注意: 您需要添加以下导入语句:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
请根据您的需求选择其中一种定位策略来点击元素。
英文:
Given the HTML:
<a id="hlExcel" href="Reports\DC_REG_638123088090882623.xls" target="_blank">
<img src="Images/Excel.gif" alt="Click to view a Excel version">
</a>
To click on the clickable element even though the file name changes every day ideally you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:
-
Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a#hlExcel > img[alt='Click to view a Excel version']"))).click()
-
Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@id='hlExcel']/img[@alt='Click to view a Excel version']"))).click()
-
Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
答案2
得分: 0
你可以尝试进行部分匹配。DC_REG是否出现在所有文件名中?如果你知道一个无论名称变化多少次都会出现在名称中的模式,你可以寻找该模式。类似于
link = browser.find_element_by_css_selector('a[href*="REG"][href$=".xls"]')
link.click()
英文:
You could go for a partial match maybe. Is the DC_REG common in all file names ? If you know a pattern which will be part of the name irrespective of how many times the name changes, you could look for that pattern. Something like
link = browser.find_element_by_css_selector('a[href*="REG"][href$=".xls"]')
link.click()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论