我正在尝试硒框架,以了解有关Web浏览器自动化的知识。因此,我决定建立一个奥迪模型...
到目前为止,我的代码:
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
chrome_driver = webdriver.Chrome(executable_path=r"chromedriver_win32\chromedriver.exe")
chrome_driver.get("https://www.audi.de/de/brand/de/neuwagen.html")
# choose A3 model
chrome_driver.find_element_by_xpath('//*[@id="list"]/div[1]/ul/li[2]/a[2]').click()
# choose sedan version
WebDriverWait(chrome_driver, 3).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="a3limo"]/div/a'))).click()
# start model configuration
WebDriverWait(chrome_driver, 3).until(EC.visibility_of_element_located((By.XPATH, '/html/body/div[1]/div[2]/div/div[6]/div[2]/div/div[1]/ul/li[1]/a'))).click()
# choose the s-line competition package
WebDriverWait(chrome_driver, 3).until(EC.visibility_of_element_located((By.XPATH, '/html/body/div[1]/div[2]/div/div[7]/div[2]/div[2]/div[3]/div[1]/div/div[1]/div/div[1]/span/span'))).click()
# accept the s-line competition package
WebDriverWait(chrome_driver, 3).until(EC.visibility_of_element_located((By.XPATH, '/html/body/div[5]/div/div/div/div/div/ul[2]/li[2]/a'))).click()
现在,代码已在行start model configuration
上失败(请参见网页https://www.audi.de/de/brand/de/neuwagen/a3/a3-limousine-2019.html上的“开始配置知识”按钮)。 xPath必须正确且元素也应该可见,所以我在这里做错了什么?
答案 0 :(得分:2)
实际上所需的链接仅在向下滚动页面时可见。
尝试使用这段代码单击链接:
configuration_start = chrome_driver.find_element_by_xpath('//a[@title="Konfiguration starten"]')
chrome_driver.execute_script('arguments[0].scrollIntoView();', configuration_start)
configuration_start.click()
由于导航面板的位置固定,它可能与目标链接重叠,因此您可以在处理链接之前更改导航面板的样式:
nav_panel = chrome_driver.find_element_by_xpath('//div[@data-module="main-navigation"]')
driver.execute_script('arguments[0].style.position = "absolute";', nav_panel)
答案 1 :(得分:1)
以下内容似乎对我有用。我添加了等待元素,并通过javascript使用了元素的模拟点击。
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
url = 'https://www.audi.de/de/brand/de/neuwagen.html'
d = webdriver.Chrome()
d.get(url)
WebDriverWait(d,10).until(EC.presence_of_element_located((By.CSS_SELECTOR, '[data-filterval="a3"]'))).click()
d.get(WebDriverWait(d,10).until(EC.presence_of_element_located((By.CSS_SELECTOR, '#a3limo .mf-model-details a'))).get_attribute('href'))
element = WebDriverWait(d,10).until(EC.presence_of_element_located((By.CSS_SELECTOR, '[title="Konfiguration starten"]')))
d.execute_script("arguments[0].click();", element)