用硒点击 Href 元素

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

代码试图点击 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-title"><a href="/games/fun-clicking-activity_~0138709d12bc7bb5ad/">Fun Clicking Game“Fun activity”</a></h3>

我试过用python和java点击,我也试过ccs和xpath,还有webdriver等等。希望代码能够找到元素,但它仍然很困难。该网站每天都会更改“游戏标题”,所以我只能使用部分链接“游戏”,因为每个游戏标题中都有,而不是完整链接。

selenium-webdriver web-scraping web-crawler href timeoutexception
2个回答
0
投票

您的代码中有一个 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')))

0
投票

我无法从我的机器访问这个 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')]
© www.soinside.com 2019 - 2024. All rights reserved.