在 Python 2.7.5 上使用 selenium 从网站下载文件。文件每天更改部分名称(日期是文件名称的一部分)

Download file from website with selenium on Python 2.7.5. File changes part of a name daily (date is part of file's name)

我有以下问题。我正在尝试编写下载文件的脚本,该文件每天都会上传到网站上。文件名是 "My Report $date.xlsx"(所以今天是“我的报告 20190917.xlsx”)。

唯一不变的值是它的标题,实际上是其中没有日期的部分。 hastooltip 和 href 正在改变。

这是我需要使用的代码:

<a class="entry-title" rel="bookmark" title="My Report 20190917.xlsx" href="https://xxxx/foo/bar/something.html" hastooltip="dijit_Tooltip_10400"><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>My Report 20190917.xlsx</a>

这是我到目前为止用谷歌搜索/尝试过的内容,我认为这非常接近:

我尝试使用 xpath 而不是 css_selector,但没有成功(title^= 而不是 title=: )

driver.find_element_by_xpath("//div[@id='list']/div[@role='region']/table[@role='presentation']/tbody/tr[15]//a[title^='My Report']").click()

我还尝试使用一些选项,例如 "title contains",并尝试使用变量而不是 'My Report' 名称,例如:

import time
my_file =("My Report " +  time.strftime("%Y%m%d") + ".xlsx")

并将 my_file 变量放入 xpath 搜索中,但这根本不起作用。

不久我就没有想法了,恳请帮助。

我认为这是一个可能的解决方案:

from selenium.webdriver.common.by import By
from datetime import datetime

today = datetime.now()
today = today.strftime("%Y%m%d")
exp = "//*[@title='My Report "+today+".xlsx']"

myfile = driver.find_element(By.XPATH,(" %s" % exp))
myfile.click()

希望对你有帮助

我相信您正在处理在线无法获得的内容。所以,我不能尝试。 我给你的表情是return这个:

Element='<a class="entry-title"
hastooltip="dijit_Tooltip_10400"
href="https://xxxx/foo/bar/something.html"
rel="bookmark"
title="My Report 20190917.xlsx"/>'

但您真正需要的是 xls 的路径。 如果xls的link就是上面的href,你可以这样做:

myfile.get_attribute('href')

不知道是下载就够了还是必须用命令打开:

driver.get(myfile.get_attribute('href'))

所需的元素是一个动态元素,因此对于 click() 您必须为 element_to_be_clickable() 引入 WebDriverWait 的元素,您可以使用以下任一方法以下解决方案:

  • 使用XPATH:

    from datetime import datetime
    date_time_now = datetime.now()
    my_string = "My Report "+date_time_now.strftime("%Y%m%d")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='entry-title' and starts-with(@title, '" + my_string + "')]"))).click()
    
  • 注意:您必须添加以下导入:

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