如何使用 Selenium Python 单击元素?

How can I click on elements using Selenium Python?

我正在尝试概括尽可能多的代码以便抓取 eBay 网站。 我现在陷入这种情况:

这是以下 URL 我开始的地方:

https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw=iphone+12&_oac=1

我想单击“更多过滤器”按钮,然后单击 select 具体 'Brand' 选项并获取可用品牌的列表。

这是我到目前为止能做的:

url = 'https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw=iphone+12&_oac=1'
driver = webdriver.Chrome()
driver.get(url)
driver.find_element_by_id('s0-14-11-0-1-2-6-2').click()

点击()后子面板打开,我得到了我需要更改的内容:

<div role="tab" class="x-overlay-aspect " data-aspecttitle="aspect-Brand" aria-selected="false" aria-controls="refineOverlay-subPanel" id="c3-mainPanel-Brand"><span class="x-overlay-aspect__label">Brand</span><svg focusable="false" aria-hidden="true" class="x-overlay-aspect__check-icon svg-icon icon-check" role="img" aria-label="Filter applied"><use xlink:href="#svg-icon-check"></use></svg></div>

如果我在 'Brand' 上手动 select(即用光标单击),这就是我得到的结果:

<div role="tab" class="x-overlay-aspect active" tabindex="0" data-aspecttitle="aspect-Brand" aria-selected="true" aria-controls="refineOverlay-subPanel" id="c3-mainPanel-Brand"><span class="x-overlay-aspect__label">Brand</span><svg focusable="false" aria-hidden="true" class="x-overlay-aspect__check-icon svg-icon icon-check" role="img" aria-label="Filter applied"><use xlink:href="#svg-icon-check"></use></svg></div>

不幸的是,我几乎不了解 Javascript 所以,虽然还有其他类似的帖子,但我不知道如何从这里继续下去才能最终获得我需要的信息。

希望您能帮到我,在此先感谢您!

点击更多过滤器然后点击品牌你需要诱导WebDriverWait for the element_to_be_clickable() and you can use either of the following :

  • 代码块:

    driver.get("https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw=iphone+12&_oac=1")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(., 'More filters')]"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Brand']"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
  • 浏览器快照: