问题
I want to use selenium with Python to open multi-tabs in one browser and scraping the real-time betting odds simultaneously with multi-tabs.
The website home page generate a list of games. However, there is no way to get the link of game unless you find the game element and use click()(the website is ajax heavy), which open the game in the same tab. My solution to open multi-tabs is to get the list of game then manually open new tab with home-page first loaded and then click on the game with different index in the list. However, I find the driver.window_handles
array always include only one item, which is the current tab instead of all the tabs I opened manually in the browser.
Can anybody tell me what goes wrong or if you can give a better solution to this issue?
The problem is simplified as the code in following:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
# create a new Firefox session
driver_temp = webdriver.Firefox()
driver_temp.implicitly_wait(30)
driver_temp.get("https://www.google.com")
body = driver_temp.find_element_by_tag_name('body')
# manually open second tab
body.send_keys(Keys.CONTROL + 't')
driver_temp.get("https://www.google.com")
body = driver_temp.find_element_by_tag_name('body')
# manually open third tab
body.send_keys(Keys.CONTROL + 't')
driver_temp.get("https://www.google.com")
body = driver_temp.find_element_by_tag_name('body')
#print the number of window_handles
print len(driver_temp.window_handles)
I have opened 3 tabs, however the len(driver_temp.window_handles) is always 1
回答1:
Selenium does not provide an API to manipulate browser tabs. You've probably noticed that applying the CTRL/COMMAND+T
"hack" to open a new tab.
See more at:
- Controlling firefox tabs in selenium
- Opening a new tab in the same window session of the browser through selenium web driver command?
Instead, open up new browser windows.
Well, to be fair, it is important to mention that the behavior is quite different in Firefox and in Chrome - if you open new tabs in Chrome, selenium would see each tab as a window with it's own handle and you'll switch between them using switch_to.window() easily.
来源:https://stackoverflow.com/questions/30258624/selenium-window-handles-not-correct-when-new-window-is-opened-wtih-python