python - (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 行),但我仍然遇到同样的错误。
其他尝试的解决方案:
使用显式等待来等待 uCard_name 元素
每次循环清除缓存/删除搜索历史
使用WebDriverWait停止程序
附加信息:
在 Pycharm 中工作,Python 版本 3.6
Windows 10、64 位
解决方案
最佳实践是对感兴趣的元素使用显式等待。这样,您在单击它或以其他方式与之交互之前就知道它在那里。
所以一定要添加这些导入:
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
...
推荐阅读
- angular - 如何在 vscode 中为 Angular 项目设置正确的 typescript linting?
- javascript - 当单击标题时新列表向下滑动时,jQuery向上滑动显示列表?
- azure-devops - 在 yaml 管道中访问 $(System.AccessToken)
- sql - presto sql查找具有按顺序插入的特定列值的ID
- r - 如何在 R 中使用循环返回每个类别的最大值?
- powershell - 如何在 Powershell 中将 Office365 中的所有教师作为所有者添加到所有 Teams
- python - 如果我使用二进制变量,CPLEX 找不到解决方案
- ios - ios adhoc 分发的 Xamarin 存档构建失败
- get - Buildfire数据库userData在使用get和save时不起作用
- java - application.css 显示“未知属性”