代码试图单击python Selenium中的href元素,但失败了。代码如下:
#provides access to the webdriver
from selenium import webdriver
#allows interraction with elements of the webpage
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
import time
#initilize a webdriver object
driver = webdriver.Chrome()
driver.get("https://www.dynamic-example.com/ab/search/fun")
# click on game title
game_title4 = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//h3[contains(@class,"game-title")]//a[contains(@href,"/games/")]/span')))
# added a loop to scroll down and up until the element is located
while not games_title4.is_displayed():
driver.execute_script("window.scrollBy(0, 100);")
game_title4 = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, '//h3[contains(@class,"game-title")]//a[contains(@href,"/game/")]/span')))
# wait for the element to become clickable
game_title4 = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '//h3[contains(@class,"games-title")]//a[contains(@href,"/games/")]/span')))
# click on the element using execute_script
driver.execute_script("arguments[0].click();", games_title4)
,这里是它试图点击的元素<div class="game-tile-badges d-flex mb-10 is-empty" data-test="gameTileBadges"><!----> <!----> <!----></div><h3 class="my-0 p-sm-right game-tile-title"><a href="/games/fun-clicking-activity_~0138709d12bc7bb5ad/">Fun Clicking Game“Fun activity”</a></h3>
我尝试点击python和java,我也尝试了CCS和xpath,和webdriver等待。期望代码能够找到元素,但它仍然挣扎。网站更改了"游戏标题"所以我每天只能使用部分链接"game"因为这是在每个游戏标题中,但不是完整的链接。
我无法从我的机器访问这个URL。根据所提供的HTML标记进行回答。
如果这是HTML元素:
<h3 class="my-0 p-sm-right game-tile-title">
<a href="/games/fun-clicking-activity_~0138709d12bc7bb5ad/">Fun Clicking Game“Fun activity”</a>
</h3>
您所构造的XPATH表达式将永远无法工作。如果仔细观察,@class
属性的值包含game-tile-title
而不是game-title
。此外,我没有看到任何span
节点。因此基于所提供的HTML的XPATH表达式应该是:
//h3[contains(@class,'game-tile-title')]//a[contains(@href,'games')]
在您的代码中有两次将XPath标记为CSS选择器:
By.CSS_SELECTOR, '//h3[contains(@class,"game-title")]//a[contains(@href,"/game/")]/span')))
这是XPath
,所以:
By.XPATH, '//h3[contains(@class,"game-title")]//a[contains(@href,"/game/")]/span')))