简体   繁体   中英

How to get link and page information of new opened tab in selenium python

i was trying to scrape this website. the process i followed was search a user click the first user and get information about him/her. after i clicked the user it is opening a new tab, so how can i get the information in the newly opened tab.

这是我搜索用户并单击的第一个页面 这是我点击每个用户时得到的第二页

the code that i have written so far

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome('C:/Users/XXX/chromewebdriver/chromedriver.exe')
driver.get('https://www.tracksellers.com/')

search = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='desktop-seller-search']")))

search.click()

word = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='d-seller-autocomplete']")))

word.send_keys('james')

searchdiv = word = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='d-seller-autocomplete-box']")))

searchresult = searchdiv.find_element_by_id('list')
searchresult = searchresult.find_elements_by_tag_name('li')

searchresult[0].click()

# the above code search's for a user and click on the first user 

# next steps i tried
driver.window_handles

# gives me the below output
['CDwindow-70F83E4DCEB9D746B96FD9D965FC1BF7',
 'CDwindow-87428C4E8AF3614CFE2C461A0B3AE765']

# trying to get the current tab by using this code, but it gives only the first tab
driver.current_window_handle

# output
'CDwindow-70F83E4DCEB9D746B96FD9D965FC1BF7'

How can i switch from one tab to another tab and access tags and other things.

It's in a new tab so you would need to switch the driver focus to the newly opened tab :

driver.switch_to.window(driver.window_handles[1])

You need to write this code right after the click on first page.

  maintab = driver.current_window_handle




  for handle in driver.window_handles:
            if handle != main_page:
              othertab = handle

 driver.switch_to.window(othertab)

After this you can use your code on tab2 Also ,with this code you can switch back to your main tab using

 driver.switch_to.window(maintab)

again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM