首页 > 解决方案 > Python Selenium 遍历表并相应地单击每一行

问题描述

我正在尝试遍历表并下载 xml 文件,但是,我只下载表中第一个元素的内容。如何正确迭代以从每一行下载内容?

row我应该在哪里包含for row in table:正确的愤怒?

from selenium import webdriver
options.add_argument("--incognito")
driver = webdriver.Chrome(options=options)

driver.get('https://fnet.bmfbovespa.com.br/fnet/publico/abrirGerenciadorDocumentosCVM?cnpjFundo=30983020000190')
driver.find_element_by_css_selector(f'input[type="search"]').click()
driver.find_element_by_css_selector(f'input[type="search"]').send_keys('rendimentos')
time.sleep(1)
table = driver.find_elements_by_xpath("//table[@id='tblDocumentosEnviados']//tr")
for row in table:
try:
WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.XPATH,"//table[@id='tblDocumentosEnviados']//td[text()='Rendimentos e Amortizações']/following-sibling::td[.//span[text()='Ativo']]/following-sibling::td//a[@title='Download do Documento']"))).click()
x = x + 1
print(x)
except:
print('except')

编辑

我需要在这一行中添加行迭代才能成功:

                try:
                    WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.XPATH,
                                                                               "//table[@id='tblDocumentosEnviados']//td[text()='Rendimentos e Amortizações']/following-sibling::td[.//span[text()='Ativo']]/following-sibling::td//a[@title='Download do Documento']"))).click()

标签: pythonselenium

解决方案


我更喜欢 BeautifulSoup,而不是使用 selenium 下载文件。将您的表格更改为下面的表格,以获得html

from bs4 import BeautifulSoup
table = driver.find_elements_by_xpath("//table[@id='tblDocumentosEnviados']")

table_html = table[0].get_attribute('outerHTML')
table_html = BeautifulSoup(table_html, 'lxml')
list_url = []

for tr in table_html.find_all('tr'):
    for td in tr.find_all('td'):
        file_anchor = td.find('a', {'title': 'Download do Documento'})
        if file_anchor:
            complete_url = 'https://fnet.bmfbovespa.com.br/fnet/publico/{}'.format(file_anchor.get('href'))
            list_url.append(complete_url)

现在你可以使用 request.get 来下载文件了,希望对你有帮助!!!

文件下载 - https://www.tutorialspoint.com/downloading-files-from-web-using-python


推荐阅读