【问题标题】:(Python, selenium) implicit and explicit wait not working(Python,硒)隐式和显式等待不起作用
【发布时间】:2018-04-28 01:29:48
【问题描述】:

我正在尝试编写一个网页抓取程序:

1) 在搜索栏中输入名称

2) 按回车键

3) 找到第一个搜索结果,这是指向另一个页面的链接

4) 点击第一个结果

5) 在结果页面上查找指定元素

6) 复制该元素

7) 在 PyCharm 中打印该元素

8) 对预加载数组中的每个条目重复(设置为“名称”)

以下是设计用于执行此操作的代码部分。

from selenium import webdriver
import time
import xlrd


driver = webdriver.Chrome("path")

i=0
while i < len(names):

    a = names[i]
    driver.set_page_load_timeout(25)
    driver.get("https://www.healthgrades.com/")

    driver.find_element_by_id("search-term-selector-child").send_keys(a)
    driver.find_element_by_id("search-term-selector- 
    child").send_keys(u'\ue007')

    driver.implicitly_wait(20)
    first = driver.find_element_by_class_name('uCard__name')
    first.click()

    driver.implicitly_wait(20)
    elem= driver.find_element_by_class_name("office-street1")

    entry1 = elem.text
    time.sleep(1)
    print(entry1)
i += 1

当我运行程序时,看起来代码在该步骤中的元素变为链接之前完成了第 4 步(第 13 行);我最常收到的错误是

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"class name","selector":"office-street1"}

我认为这意味着它通过 find_element_by_class_name 并执行点击。但是当我观看自动网页时,我注意到下一页永远不会打开。

为了解决这个问题,我尝试在搜索 uCard 元素之前进行隐式等待(第 15 行),但我仍然遇到同样的错误。

其他尝试的解决方案:

  • 使用显式等待来等待 uCard_name 元素

  • 每次循环清除缓存/删除搜索历史

  • 使用WebDriverWait 停止程序

附加信息:

  • 使用 Pycharm,Python 3.6 版

  • Windows 10,64 位

【问题讨论】:

  • 一旦驱动程序停止,类就存在于 DOM 中?

标签: python selenium web-scraping wait


【解决方案1】:

最佳做法是对感兴趣的元素使用显式等待。这样您在点击它或与之交互之前就知道它就在那里。

所以一定要添加这些导入:

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome("path")

# Only need to do this once per session
driver.implicitly_wait(20)

i=0
while i < len(names):

    a = names[i]
    driver.set_page_load_timeout(25)
    driver.get("https://www.healthgrades.com/")

    driver.find_element_by_id("search-term-selector-child").send_keys(a)
    driver.find_element_by_id("search-term-selector-child").send_keys(u'\ue007') 

    first = driver.find_element_by_class_name('uCard__name')
    first.click()

    timeout = 20
    # Explicitly wait 20 seconds for the element to exist.
    # Good place to put a try/except block in case of timeout.
    elem = WebDriverWait(driver, timeout).until(
           EC.presence_of_element_located(('className', 'office-street1'))
           )
    entry1 = elem.innerText
    ...

【讨论】:

  • The best practice is to use an explicit wait for the element of interest. 我真的很想知道您在哪里可以找到这些最佳做法。
  • 隐式和显式等待同时使用有什么意义?
猜你喜欢
  • 2018-08-05
  • 2020-01-20
  • 1970-01-01
  • 2022-06-22
  • 1970-01-01
  • 1970-01-01
  • 2018-12-15
  • 2017-07-17
  • 2020-12-26
相关资源
最近更新 更多