首页 > 解决方案 > (Python,硒)隐式和显式等待不起作用

问题描述

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

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 行),但我仍然遇到同样的错误。

其他尝试的解决方案:

附加信息:

标签: pythonseleniumweb-scrapingwait

解决方案


最佳实践是对感兴趣的元素使用显式等待。这样,您在单击它或以其他方式与之交互之前就知道它在那里。

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

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
    ...

推荐阅读