如何使用Selenium单击没有id的标签

2024-04-28 04:40:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用这个网站测试任何https://www.nike.com.br/cosmic-unity-153-169-211-324680 几秒钟后,我尝试加载页面,您必须选择大小,而我无法使用Selenium自动选择大小。有人能帮我吗

看,当你选择运动鞋的尺寸时,我在巴西,我选择了运动鞋的尺寸40,只有当你检查“40”时,你才会看到它是一个标签,并且这个标签没有id,这个标签是以下html代码片段:

<label for="tamanho__id40">40</label>

我如何点击Selenium中的标签

我目前有以下代码:

import datetime                                 
from selenium import webdriver          
from selenium.webdriver.chrome.options import Options                                           
from selenium.webdriver.common.desired_capabilities
import DesiredCapabilities from selenium.webdriver.support.ui 
import WebDriverWait from selenium.webdriver.common.by 
import By from selenium.webdriver.support 
import expected_conditions as EC                                
import time
                                            
option = Options()                              
prefs = {'profile.default_content_setting_values': {'images': 2}}                                
option.add_experimental_option('prefs', prefs)  
driver = webdriver.Chrome(options = option)   
# Navigate to url                                
driver.get"https://www.nike.com.br/cosmic-unity-153-169-211-324680")

我需要添加什么才能点击这个没有id的标签?


Tags: fromhttpsbrimportcomwwwseleniumunity
1条回答
网友
1楼 · 发布于 2024-04-28 04:40:31

1您需要接受cookies

2使用Selenium的显式等待。要使用它们,您需要导入:

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

3使用可靠的定位器。我建议使用这个xpath定位器来定位40码的鞋子://label[@for="tamanho__id40"]

4我添加了一些chrome_options来处理这个站点

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(" disable-blink-features")
chrome_options.add_argument(" disable-blink-features=AutomationControlled")
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36")
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(executable_path='/snap/bin/chromium.chromedriver', options=chrome_options)
driver.get("https://www.nike.com.br/cosmic-unity-153-169-211-324680")
wait = WebDriverWait(driver, 15)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.cc-allow'))).click()
wait.until(EC.element_to_be_clickable((By.XPATH, '//label[@for="tamanho__id40"]'))).click()

相关问题 更多 >