【问题标题】:Need to click download button that matches the given text需要单击与给定文本匹配的下载按钮
【发布时间】:2020-10-05 18:17:49
【问题描述】:

我正在尝试下载在表格中写有税务发票的发票,我遍历表格元素并获取所需的详细信息。但是当我点击下载按钮时,它会下载同一张发票两次。如何让它下载第二张“税务发票”?下图是:

和html代码:

下面是代码:

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




driver = webdriver.Chrome(executable_path=r'D:/Chrome driver/chromedriver.exe')
driver.get("the link")

time.sleep(10)

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="GST"]/div/div/a[2]/span[1]'))).click()

driver.switch_to.frame('ifgstdownloadnFrame')
driver.find_element_by_xpath('//*[@id="txtpnr"]').send_keys('QYJ27J')

driver.find_element_by_xpath('//*[@id="btnSubmit"]').click()

mytable = driver.find_element_by_css_selector("table.gstInvoiceGrid")

for row in mytable.find_elements_by_css_selector('tr'):
    for cell in row.find_elements_by_tag_name('td'):
        if 'Tax Invoice' in cell.text:
            print()
            driver.find_element_by_css_selector('input.download.downloadbutton').click()
time.sleep(10)
            
#driver.quit()

【问题讨论】:

  • 这一行: driver.find_element_by_css_selector('input.download.downloadbutton').click() 与您所在的行无关。我会尝试一个以 id 或发票为目标的选择器。这使得代码更简单。无需查找表格或行/单元格。
  • 表格不断变化,有时它会有四个条目,有时是六个甚至两个,所以我匹配了文本,并且由于表格中的条目不会被修复,所以 id 会不断变化。跨度>
  • //td[text()='Tax Invoice']/../td:last-child/input 应该找到所有要点击的输入标签
  • 感谢您的回答。我使用的是驱动程序而不是行,这就是它下载第一张税务发票的原因。

标签: python selenium selenium-webdriver automation


【解决方案1】:

您需要更改逻辑以使用dot 查找intermediate 单元格,使用以下任一代码逻辑,该逻辑将单击每个具有Tax Invoice 的下载按钮。

for row in mytable.find_elements_by_css_selector('tr'):
    for cell in row.find_elements_by_xpath('./td'):
        if 'Tax Invoice' in cell.text:
            print()
            row.find_element_by_xpath(".//input[@value='Download']").click() 

或者

for row in mytable.find_elements_by_css_selector('tr'):
    if row.find_element_by_xpath("./td[text()='Tax Invoice']"):
        row.find_element_by_xpath(".//input[@value='Download']").click()

【讨论】:

  • 感谢您的回答。适用于 'row.find_element_by_xpath(".//input[@value='Download']").click() '。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-10
  • 2019-07-15
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
  • 2018-04-06
相关资源
最近更新 更多