Python Selenium 循环链接 [英] Python Selenium Loop Through Links
问题描述
我是python的新手,或者对此事进行编码...
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()
显然,此for循环仅打开链接.我对如何添加这样的东西很感兴趣,以收集一些数据:
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?
????
如何在整个for循环中实现此目标.换句话说,我想进入每个链接并收集一些数据.是否可能?一些建议或示例代码?
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?
推荐答案
您可以尝试以下允许循环处理具有匹配结果的窗口的代码:
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
这篇关于Python Selenium 循环链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!