【发布时间】:2016-01-04 18:51:57
【问题描述】:
她是我的代码基本上所做的(或者我正在尝试做的)。打开一个窗口,从页面打开一个链接,从页面获取一些数据并关闭选项卡。问题在于关闭选项卡。再次打开第二个链接并再次执行相同的操作。
link.send_keys(Keys.CONTROL + 'w')
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 323, in send_keys
self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': typing})
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 404, in _execute
return self._parent.execute(command, params)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 195, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 170, in check_response
raise exception_class(message, screen, stacktrace)
StaleElementReferenceException: Message: Element belongs to a different frame than the current one - switch to its containing frame to use it
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time
from lxml import html
import requests
import xlwt
browser = webdriver.Firefox() # Get local session of firefox
# 0 wait until the pages are loaded
browser.implicitly_wait(3) # 3 secs should be enough. if not, increase it
browser.get("http://ae.bizdirlib.com/taxonomy/term/1493") # Load page
links = browser.find_elements_by_css_selector("h2 > a")
def test():#test function
elems = browser.find_elements_by_css_selector("div.content.clearfix > div > fieldset> div > ul > li > span")
browser.implicitly_wait(3) # 3 secs should be enough. if not, increase it
for elem in elems:
print elem.text
elem1 = browser.find_elements_by_css_selector("div.content.clearfix>div>fieldset>div>ul>li>a")
browser.implicitly_wait(3) # 3 secs should be enough. if not, increase it
for elems21 in elem1:
print elems21.text
return
for link in links:
link.send_keys(Keys.CONTROL + Keys.RETURN)
link.send_keys(Keys.CONTROL + Keys.PAGE_UP)
browser.switch_to_window(browser.window_handles[-1])
test() # Want to call test function
browser.implicitly_wait(3) # 3 secs should be enough. if not, increase it
# browser.quit()
browser.switch_to_window(browser.window_handles[0])
link.send_keys(Keys.CONTROL + 'w')
# browser.switch_to_window(browser.window_handles[0])
【问题讨论】:
-
在哪个迭代中失败了?第一,第二,还有别的吗?
-
第二次迭代失败。在第一次迭代中,它打开一个选项卡并获取我想要的数据。当我想关闭选项卡并打开下一个链接时。我无法关闭它...
-
@PythonLearner - 我的回答对你有帮助吗?
标签: python python-2.7 selenium selenium-webdriver web-scraping