我正在尝试编写一个网络剪贴程序:
1(在搜索栏中键入名称
2(按Enter
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
...