使用selenium和phantomjs从两个投递箱的所有组合中加载内容

时间:2013-08-14 19:44:44

标签: python selenium phantomjs

我想通过Selenium和HhantomJS使用Python 2.7绑定自动完成工作。问题是我试图自动化的网站有两个dropbox。第一个保管箱加载第二个保管箱的内容,第二个保管箱依次加载网站上的内容。

我想得到这一切的所有组合。所以我写了下面的代码:

with contextlib.closing(webdriver.PhantomJS(phantomjs)) as driver:
driver.get(URL)
soup = BeautifulSoup(driver.page_source,"lxml")
firstmenu = driver.find_element_by_name("ctl00$Body$Browse1$ddlFosList");
firstmenuoptions = firstmenu.find_elements_by_tag_name('option')
firstmenuoptionsiter =iter(firstmenuoptions)
next(firstmenuoptionsiter)
for firstmenuoption in firstmenuoptionsiter:
    firstmenuoption.click()
    wait = ui.WebDriverWait(driver, 60)
    wait.until(lambda driver: driver.find_element_by_name("ctl00$Body$Browse1$ddlFosList"))
    secondmenu = driver.find_element_by_id("ctl00_Body_Browse1_ddlCourseBlockList")
    secondmenuoptions = secondmenu.find_elements_by_tag_name('option')
    for secondmenuoption in secondmenuoptions:
        print secondmenuoption.text

但是,我在print secondmenuoption.text行获取StaleElementReference异常。这可能是因为在选择第一个菜单时页面会重新加载。关于如何进行的任何想法?

1 个答案:

答案 0 :(得分:0)

我遇到了StaleElementReference异常的一些问题,我能想出的最佳解决方案是添加Thread.sleep()。您不能等待某些预期条件,因为第二个保管箱中的所有元素都已加载。

Selenium确实刷新了这个函数(ExpectedCondition条件),所以你可以尝试一下。否则,我认为Thread.sleep()是一个有效(但很糟糕)的解决方案。