Python Selenium循环通过链接

时间:2017-03-15 16:05:12

标签: python loops selenium

我是python的新手,或为此事编码...

这部分代码允许我找到我想要点击的所有元素(点击链接打开一个新标签)

# 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?
????

显然这个for循环只打开链接.. 我对如何添加这样的东西感兴趣,以收集一些数据:

cloisterville

如何在for循环中实现这一点..换句话说,想要进入每个链接并收集一些数据..是否可能?一些建议或示例代码?

1 个答案:

答案 0 :(得分:2)

您可以尝试以下代码,以便在循环中处理具有匹配结果的每个窗口:

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
相关问题