Python Selenium Loop Through Links

人盡茶涼 提交于 2021-02-07 04:15:17

问题


Im new to python, or coding for that matter...

This part of the code allows me to find all the elements that I want to click (click on the link open a new tab)

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("http://www.rezultati.com/kosarka/filipini/kup/")

list_of_links = driver.find_elements_by_css_selector(".cell_ad.time")
for link in list_of_links:
    link.click()

Obviously this for loop only opens links.. I'm interested in how to add, somethin like this, to collect some data:

# wait to open link
time.sleep(3) 
# handle new window
newtab = driver.current_window_handle
driver.switch_to_window(newtab)
# collecting data and print data
date = driver.find_elements_by_class_name("mstat-date")
for d in date:
    print(d.text)
# Some code to close newtab?
????

How do I implement this throughout the for loop.. In other words want to go in every link and collect some data.. Whether it is possible? Some suggestions or examples code?


回答1:


You can try below code that allow to handle each window with match results in a loop:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://www.rezultati.com/kosarka/filipini/kup/")

list_of_links = driver.find_elements_by_css_selector(".cell_ad.time")
cur_win = driver.current_window_handle # get current/main window

for link in list_of_links:
    link.click()
    driver.switch_to_window([win for win in driver.window_handles if win !=cur_win][0]) # switch to new window
    date = driver.find_elements_by_class_name("mstat-date")
    for d in date:
        print(d.text)
    driver.close() # close new window
    driver.switch_to_window(cur_win) # switch back to main window


来源:https://stackoverflow.com/questions/42814991/python-selenium-loop-through-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!