【问题标题】:How to handle selenium python script when element is already present on page?当页面上已经存在元素时如何处理 selenium python 脚本?
【发布时间】:2021-05-25 23:08:05
【问题描述】:

我正在抓取一个小站点,其中我循环将 send_keys 发送到一个文本框,然后单击搜索按钮,页面加载一些结果,我检查存在_of_element,最后我得到这些结果的文本。 但问题是当网站打开时,它已经在页面上显示了一些结果,因此当搜索循环开始并单击搜索按钮时,页面需要几秒钟才能加载新结果,但脚本会继续并selenium 看到初始结果的存在并再次捕获它们,循环继续以相同的结果。我尝试添加 time.sleep 但仍然遇到一些问题。下面是工作流程和代码

URL Opens
Result 0 already present on page
Change Dropdown
Loop starts>>
Text sent to searchBox >> Search button Clicked
Result 0 still present on Site
Page is loading >> But Selenium sees presence of Result0 and gets text
Loop continues to send new key and click search button
Page is still loading with Result 1>> selenium again checks presence and this continues.

self.driver.get(self.url)
self.waitForPresenceOfElement(locator=self.radius_drop_down, locatorType='id')
self.dropByType(data='100', locator=self.radius_drop_down, locatorType='id', type='value')
time.sleep(6)
for state in self.states:
    self.sendKeysWhenReady(data=state, locator=self.search_box, locatorType='id')
    time.sleep(1)
    self.elementClick(locator=self.search_button, locatorType='xpath')
    time.sleep(3)
    if self.getElementList(self.storesXpath, locatorType='xpath'):  # to ignore Empty states
        stores = self.waitForPresenceOfAllElements(locator=self.storesXpath, locatorType='xpath')
        for store in stores:  
            self.full_list.append(self.getText(element=store).lower())

【问题讨论】:

  • 我们似乎遗漏了您的大部分代码。什么是self.radius_drop_down;或self.waitForPresenceOfElement()sendKeysWhenReady()...
  • 计算元素。 find_elements 将返回所有出现的事件,您可以通过返回列表的大小来跟踪。
  • @C.Peck 此代码由编写的自定义函数组成,因此 radius_drop_down 之类的只是一个定位器,self.waitForPresenceOfElement() 是一个自定义方法,用于检查元素是否存在。不确定所有这些代码是否与此处相关。问题是当元素点击发生时,页面需要几秒钟才能加载,但脚本向前移动并找到已经存在的元素,这就是导致问题的原因
  • 您应该考虑使用waitForElementToBeClickable(element) 之类的方法,这比对元素是否存在进行加权更有效。 (它确认元素存在、显示和启用。

标签: python selenium selenium-webdriver


【解决方案1】:

解决这个问题的方法是:

  1. 开始你的循环。

  2. 在页面上查找现有的搜索结果并获取对它的引用。

    result = driver.find_element(...)
    
  3. 发送搜索词并点击搜索。

  4. 等待 result 引用失效,这会告诉您页面正在重新加载。

     wait = WebDriverWait(driver, 10)
     wait.until(EC.staleness_of(result))
    
  5. 等待结果可见并继续循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多