【问题标题】:Keeping scrolling down until it located the respective Filter(Element?) and click it - Selenium Python继续向下滚动,直到找到相应的过滤器(元素?)并单击它 - Selenium Python
【发布时间】:2021-09-13 16:47:52
【问题描述】:

嗨,我目前正在做 selenium Python。场景是这样的:我目前试图找到某个“元素”或者说过滤器(因为我在网上商店做硒),例如我想找到一个过滤器名称:“LCD”。
结果是错误。问题是这个 LCD 不在屏幕上,这意味着我需要向下滚动,直到该过滤器出现或在屏幕上可见,然后我才能单击它。问题是我不知道正确的代码,或者我可能编码错误。我的代码是这样的:

我的浏览器将继续向下滚动(条件“除外”),直到找到我选择的元素过滤器。问题是它没有点击。是的,它出现在屏幕上,但没有点击(应该是“尝试”的条件)。

while finding_click is False:
    try:
        driver.find_element_by_xpath('//*[contains(text(),"' + filtchooseText + '")]').click()
        finding_click = True
    except:
        driver.execute_script("window.scrollTo(0, {});".format(scroll))
        scroll = scroll + 20

我想知道怎么了?我想知道如果这是错误的代码是什么?继续向下滚动,直到找到相应的元素然后单击它...?

我使用的软件:Pycharm、Selenium

【问题讨论】:

    标签: python selenium scroll pycharm element


    【解决方案1】:

    如果浏览器处于全屏模式,那么下面的代码应该适合您。

    最大化它:

    driver.maximize_window()
    driver.get("some URL")
    

    然后使用 ActionChains 找到过滤器并点击它:

       while True:
            try:
                ActionChains(driver).move_to_element(driver.find_element_by_xpath('//*[contains(text(),"' + filtchooseText + '")]')).click().perform()
                break
            except:
                driver.execute_script("window.scrollTo(0, {});".format(scroll))
                scroll = scroll + 20
    

    【讨论】:

      【解决方案2】:

      我推荐这个

      先导入这个

      from selenium.common.exceptions import NoSuchElementException
      from selenium.webdriver.common.keys import Keys
      

      然后像这样使用

      while finding_click is False:
              try:
                  driver.find_element_by_xpath('//*[contains(text(),"' + filtchooseText + '")]').click()
                  finding_click = True
              except NoSuchElementException:
                  driver.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN)
                  sleep(randint(2, 3))
                  continue
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-23
        • 2018-08-25
        • 2020-07-04
        • 2021-12-26
        • 1970-01-01
        • 1970-01-01
        • 2020-07-09
        • 1970-01-01
        相关资源
        最近更新 更多