使用 selenium 定位 svg 元素

问题描述 投票:0回答:1

我正在尝试自动化从下面的网站下载股票的过程,最初从一只股票开始:Turkiye Sigorta(我有订阅,我希望您可以访问该 URL):

https://fintables.com/sirketler/TURSG/finansal-tablolar/gelir-tablosu?period=&type=¤cy=usd

检查“Excel'e Aktar”文本(需要单击以下载 Excel 中的财务数据)的文本,我注意到它位于 svg 元素内。

您能否帮忙解决目前无法使用的代码:

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
from selenium.common.exceptions import NoSuchElementException, TimeoutException

url = 'https://fintables.com/sirketler/TURSG/finansal-tablolar/bilanco?period=&type=&currency=usd'

driver = webdriver.Chrome()
driver.maximize_window()
driver.get(url)

try:
    svg_element = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,"//*[name()='svg']")))

    # Find the specific SVG element containing the text 'Excel'e Aktar' (with capital 'A')
    excel_button_svg = svg_element.find_element(By.XPATH, f".//*[contains(text(), \"Excel'e Aktar\")]")

    # Click the 'Excel'e Aktar' button within the SVG
    excel_button_svg.click()

except NoSuchElementException:
    print("SVG or button not found")
except TimeoutException:
    print("Timed out waiting for SVG element to be clickable")
except Exception as e:
    print(f"An unexpected error occurred: {str(e)}")

感谢您的帮助和时间,非常感谢!在您的帮助下成功解决此问题后,我将尝试自动下载超过 550 只股票。

python html selenium-webdriver htmlelements
1个回答
0
投票

下载按钮实际上不在 SVG 内部......它是它的兄弟。下面的代码有效

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

url = 'https://fintables.com/sirketler/TURSG/finansal-tablolar/bilanco?period=&type=&currency=usd'
driver = webdriver.Chrome()
driver.maximize_window()
driver.get(url)

wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, "//div[text()=\"Excel'e Aktar\"]"))).click()
© www.soinside.com 2019 - 2024. All rights reserved.