无法在 selenium 中选择 google 个框选项卡

Trouble selecting google one box tab in selenium

要去 https://www.google.com/search?q=tennis 一个 google 一个框出现得分,我试图点击选项卡和(女子单打,男子双打等)但没有运气。我已经尝试了所有方法,xpath、类名、部分 link 文本、css 选择器。

任何帮助将不胜感激!!!

我总是使用这种方法在基于 Selenium 的 Python 项目中设置 XPath。

  1. 打开后按F12 link
  2. 在元素中,单击 Ctrl + F。现在在页面中搜索一些独特的术语。我给了男单,然后出现了这个片段。
<div class="SVWlSe FZzi2e" jsslot="">
    <span jsslot="">
       <div aria-controls="_dtAkYIqaMLraz7sPnrW54A435_0" 
            id="_dtAkYIqaMLraz7sPnrW54A434_0">
            <span>
                <span>Men's Singles</span>
             </span>
       </div>
    </span>
</div>
  1. 现在右键单击代码片段以获取 XPath 格式或使用 XPath 语法。这里,XPath 是 //div[@class='SVWlSe FZzi2e']。要查找属性值是否唯一,我建议您使用该值再次在元素内搜索。

请注意,我使用了 class 属性而不是 aria-controls 和 id 属性,因为 id 和 aria-controls 随着时间的推移而改变。

所需的元素是 JavaScript enabled element, so ideally, to click on the element you need to induce WebDriverWait for the and you can use either of the following :

  • 点击女单:

    driver.get('https://www.google.com/search?q=tennis')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@jsslot]//span//span[contains(., 'Women') and contains(., 'Singles')]"))).click()
    
  • 点击男双:

    driver.get('https://www.google.com/search?q=tennis')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@jsslot]//span//span[contains(., 'Men') and contains(., 'Doubles')]"))).click()
    
  • 注意:您必须添加以下导入:

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