这就是我的代码基本上所做的(或者我正在尝试做的)。打开一个窗口,从页面打开一个链接,从页面获取一些数据并关闭选项卡。问题在于关闭选项卡。再次打开第二个链接,再次执行相同的操作。
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])
请您参考如下方法:
switch_to_window当您在多个窗口而不是不 选项卡上工作时,将使用此功能。因此,使用该功能是无用的。根据这个link ,到目前为止,Selenium 官方不支持选项卡当您执行
link.send_keys(Keys.CONTROL + 'w')时,请注意link元素不属于显示的当前选项卡.因此,您应该从当前选项卡中选择一个随机元素,然后调用send_keys函数。
你的 for 应该是这样的:
for link in links:
link.send_keys(Keys.CONTROL + Keys.RETURN)
link.send_keys(Keys.CONTROL + Keys.PAGE_UP)
test()
#Here, 'r' is the random element
r = browser.find_element_by_css_selector("h2 > a")
r.send_keys(Keys.CONTROL + 'w')
