我只是一个编程初学者,我正在尝试学习如何自动化 Web 程序。 我的工作基于https://www.coeweb.istat.it/ 。
我需要找到页面的元素,我已经尝试过
与 driver.find_element_by_xpath
但由于我对 html 代码不太熟悉,我什至不确定是否使用正确的代码片段作为该方法的参数。
有人可以向我发送代码示例以单击链接 qui.
请在页面中间以粗体显示?
这是我尝试过的:
from selenium import webdriver
from selenium.webdriver.common.by import By
url = "https://www.coeweb.istat.it/"
driver = webdriver.Chrome()
driver.get(url)
link = driver.find_element_by_xpath('//[@id="AutoNumber1"]/tbody/tr[3]/td[2]/p[3]/font/a/strong')
link.click()
不过,我得到的错误是:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="AutoNumber1"]/tbody/tr[3]/td[2]/p[3]/font/a/strong"}
最佳答案
您必须等到它可以点击:
# I have fixed xpath
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//*[@id='AutoNumber1']//a[contains(., 'qui.')]"))
)
element.click()
注意:您必须进行一些导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
还可以使用 CSS 选择器来定位元素:
#AutoNumber1 > tbody > tr:nth-child(3) > td:nth-child(2) > p:nth-child(3) > font > a
和
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "#AutoNumber1 > tbody > tr:nth-child(3) > td:nth-child(2) > p:nth-child(3) > font > a"))
)
element.click()
编辑:您必须先切换到框架,然后才能像这样找到元素:
driver.switch_to.frame(driver.find_element_by_xpath("//frame[@name = 'principale']"))
所以完整的代码将是这样的:
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
url = "https://www.coeweb.istat.it/"
driver = webdriver.Chrome()
driver.get(url)
driver.switch_to.frame(driver.find_element_by_xpath("//frame[@name = 'principale']")) # switches to frame
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//*[@id='AutoNumber1']//a[contains(., 'qui.')]"))
)
element.click()
driver.switch_to.default_content() # switch back to default content
说明:您无法与 iframe
或 frame
中的元素进行交互。为了能够做到这一点,您必须找到一个框架
,切换到它,执行一些操作,然后切换回默认内容
关于python - 如何使用 python 单击此带有 selenium 的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51195502/