我需要遍历并从一百万个网页中抓取一个元素(所有页面的类名相同)。我已通过以下(简化)方式设置了代码:
driver = webdriver.Firefox()
wait = WebDriverWait(driver,10)
detail_dict = {}
for i in range(1000000):
url = f'http://www.cnappc.it/risultato.aspx?IDAssociato={i}&tipo=1#edit'
driver.get(url)
elem_detail = wait.until(expected_conditions
.presence_of_element_located((By.CLASS_NAME,'content')))
detail_dict[i] = elem_detail.text
代码运行得相当顺利,当我中断内核进行检查时,我注意到i
和url
每次迭代都在增加。但是,驱动程序网页卡在第一个URL“ http://www.cnappc.it/risultato.aspx?IDAssociato=0&tipo=1#edit”上,因此elem_detail.text
一遍又一遍地返回相同的字符串。尽管driver.get(url)
等待页面完全加载,但驱动程序网页似乎无法跟上.get()
方法。
来自Selenium-Python/Getting Started:
driver.get方法将导航到URL给定的页面。 WebDriver将等待页面完全加载(即,已触发“ onload”事件),然后再将控制权返回给测试或脚本。
我插入了elem_detail
的预期条件,无济于事。在time.sleep(2)
之后设置driver.get(url)
可以使驱动程序网页更改并显示不同的内容,但是那样我会遇到严重的问题。即使那样,该页面仍会不时卡住,并且字典值条目最终会不系统地重复。
您能推荐一种不涉及time.sleep()
的健壮方法吗?
仅供参考:我正在将硒与壁虎驱动程序一起使用。