使用 Selenium 获取元素的绝对引用

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

我是 Selenium 的新手。我正在创建第一个示例,我访问一个网站 (https://mediamarkt.es),然后搜索特定产品。我的代码能够获取搜索 ID 并输入产品名称,然后进行搜索。然后,我想获取产品价格,但出现错误。页面如下所示:

此外,这是它的 HTML 检查:

我的目的是获得检查过的元件(参见最后一张照片的右侧部分),这样我就可以获得价格。我意识到,当我使用 ID 使用 find_element 时,它会正确获取元素,但是当我使用 ClASS_NAME 时,它找不到它。

这是目前的完整代码:

from selenium.webdriver.common.by import By
from seleniumbase import Driver
from selenium.webdriver.common.keys import Keys

driver = Driver(uc=True)

driver.get("https://www.mediamarkt.es/")

############## Accept Cookies##############
input_element = driver.find_element(By.ID, "pwa-consent-layer-accept-all-button")
input_element.click()

############## Product Search ##############
input_element = driver.find_element(By.ID, "search-form")
input_element.send_keys("3HB4131X2" + Keys.ENTER)

############## Check Product ERROR HERE##############
input_element.clear()
input_element = driver.find_element(By.CLASS_NAME, 'sc-3f2da4f5-0 dievjx sc-b45c0335-2 fWUVlw')

所以,我目前的做法是:

input_element = driver.find_element(By.CLASS_NAME, 'sc-3f2da4f5-0 dievjx sc-b45c0335-2 fWUVlw')

这是“父亲”的类名。我期待着得到这个元素。但是,它给了我错误,指出无法找到该元素。

python google-chrome selenium-webdriver
1个回答
0
投票

sc-3f2da4f5-0 dievjx sc-b45c0335-2 fWUVlw
这些是多个类,而不仅仅是一个。所以
By.CLASS_NAME
选择器将不起作用。

更改此:

By.CLASS_NAME, 'sc-3f2da4f5-0 dievjx sc-b45c0335-2 fWUVlw'

致:

By.XPATH, "//span[@class='sc-3f2da4f5-0 dievjx sc-b45c0335-2 fWUVlw']"

代码:

input_element = driver.find_element(By.XPATH, "//span[@class='sc-3f2da4f5-0 dievjx sc-b45c0335-2 fWUVlw']")
© www.soinside.com 2019 - 2024. All rights reserved.