我为这个页面(http://www.bobaedream.co.kr/cyber/CyberCar.php?gubun=I)做了一个爬虫来收集特定制造商的库存列表。我的代码从选择搜索菜单第一行中的下拉菜单开始。
每个右侧下拉菜单都是其左侧下拉菜单的子菜单。我想要做的是选择每个下拉菜单中的第一个项目,然后单击“搜索”按钮进行第一次运行。在抓取它的股票列表后,我设置了最后一个下拉菜单的第二项,然后单击"search“按钮。(如果最后一个下拉菜单中只有一个项目,则转到倒数第二个下拉菜单,然后选择其中的第二个项目。)
但问题发生在这里。我将每个下拉菜单中的每一项都保存为元组。当我尝试调用第二轮爬行的最后一个下拉菜单的第二项时,出现了"StaleElementReferenceException“或"NoSuchElementException”,并显示消息"Element is no attached to the DOM“。因此,我希望在每次下拉菜单迭代完成之前进行驱动。
下面是我的代码,但仍然有错误消息。我的错误通常发生在第二个while循环中。此时,我添加了一些“等待”函数和“刷新”函数。有时在我的代码中跳出while循环会有所帮助,但通常会陷入while循环和无限重复中。我猜第二个"try“函数中的某种类型的"wait.until(EC.~)”代码可以解决这个问题,但我没有具体的想法。请帮助我或给我任何建议。
def option2_menu_loaded(inDriver):
path = '//select[@id="level2_no"]'
return inDriver.find_element_by_xpath(path)
self.wait.until(option2_menu_loaded)
while True:
try:
select_option2_values = [
('%s' % o.get_attribute('text'), '%s' % o.get_attribute('value'))
for o
in Select(self.driver.find_element_by_css_selector("#level2_no")).options
if o.get_attribute('text') != '세부등급']
except (StaleElementReferenceException, NoSuchElementException):
print("=======Exception Found - Option2 Save=====")
self.driver.refresh()
self.driver.implicitly_wait(1.5)
continue
break
for option2 in select_option2_values:
self.csv.setCarTitle(ma, mo, de, option1[0], option2[0])
print(option2[0], option2[1])
self.driver.implicitly_wait(0.5)
while True:
try:
Select(self.driver.find_element_by_css_selector("#level2_no")).select_by_value(option2[1])
except (StaleElementReferenceException, NoSuchElementException):
print("=======Exception Found - Option2 Request=====")
self.driver.refresh()
self.driver.implicitly_wait(1.5)
self.driver.refresh()
continue
break
发布于 2017-02-05 10:24:36
这意味着包在查找元素和使用element对象之间重新加载,确保页面首先加载,并在每次需要使用时搜索元素。
一个额外的检查是在执行select之前为元素添加额外的等待,因为find_element_by_css_selector
根本不会等待元素可用。
顺序应为:页面已加载>等待元素存在>对元素执行操作
https://stackoverflow.com/questions/42047928
复制