【问题标题】:How can I click on elements using Selenium Python?如何使用 Selenium Python 单击元素?
【发布时间】:2021-03-31 04:05:01
【问题描述】:

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

这是我开始的以下 URL:

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

我想点击“更多过滤器”按钮,然后专门选择“品牌”选项并获取可用品牌的列表。

这是我迄今为止能够做到的:

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()

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>

如果我在“品牌”上手动选择(即用光标单击),这就是我得到的结果:

<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,虽然还有其他类似的帖子,但我不知道如何从这里继续下去,以便最终获得我需要的信息。

希望您能帮上忙,在此先感谢您!

【问题讨论】:

    标签: python-3.x selenium selenium-webdriver xpath webdriverwait


    【解决方案1】:

    要点击更多过滤器,然后点击品牌,您需要为element_to_be_clickable() 诱导WebDriverWait,您可以使用以下任一Locator Strategies

    • 代码块:

      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
      
    • 浏览器快照:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 2019-10-23
      • 2022-11-01
      • 1970-01-01
      • 2021-12-28
      • 2021-12-09
      相关资源
      最近更新 更多