python - 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()
解决方案
我更喜欢 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
推荐阅读
- r - 从嵌套列表中提取具有特定名称的所有元素
- c# - 如何将 C# 加密代码传递给 TypeScript?
- php - 我将如何在我的控制器中跟踪分页值并在每页显示一定数量的记录?
- sql - 如何使用 Laravel 在 SQLITE3 数据库的列中获取前 3 个最常见的数字?
- reactjs - 做出反应。更改选择后状态不会更改
- mysql - 如何使用 mysqldump 备份 mysql?
- php - 将文件上传到特定位置 PHP
- php - 显示菜单类别并列出每个菜单类别下的所有菜单并返回json数据
- javascript - 正在努力运行 Storybook
- excel - 如何计算一列对多列的所有组合