我只是编程的初学者,我正在尝试学习如何使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"}
答案 0 :(得分:2)
您必须等待,直到其可点击:
# 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
中的元素进行交互。为此,您必须找到一个frame
,切换到它,进行处理,然后再切换回默认内容
答案 1 :(得分:2)
根据URL,您已将链接与文本共享为 qui 。<frame>
与from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument('disable-infobars')
driver=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
url = "https://www.coeweb.istat.it/"
driver.get(url)
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,"principale")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//table[@id='AutoNumber1']//tr//td//p//a[@href='lnkdati.htm' and .//strong[contains(.,'qui.')]]"))).click()
相同。因此,您必须切换到所需的诱发 WebDriverWait 的帧,然后再次寻找 WebDriverWait ,同时注意以下元素:
代码块:
{{1}}
浏览器快照: