首页 > 解决方案 > 在 for 循环中更改循环字符串

问题描述

这是我之前的问题的后续问题

driver = webdriver.Chrome(executable_path="C:/Users/Joonas/PycharmProjects/Dictionaries/chromedriver.exe")
driver.get("http://naturalstattrick.com/games.php")
driver.minimize_window()
away_team = driver.find_element_by_xpath("//*[@id='teams_wrapper']/div[2]/div[3]/div[2]/div/table/tbody/tr[1]/td[2]") #Arizona
home_team = driver.find_element_by_xpath("//*[@id='teams_wrapper']/div[2]/div[3]/div[2]/div/table/tbody/tr[2]/td[2]") #Vegas
print(away_team.text, home_team.text)

输出:

Arizona Coyotes Vegas Golden Knights

我想循环上面提到的字符串,以便在每次循环后 (Game) /tr[ ] 发生变化。下一场比赛的球队阵容如下:

"//*[@id='teams_wrapper']/div[2]/div[3]/div[2]/div/table/tbody/tr[3]/td[2]" #Chicago
"//*[@id='teams_wrapper']/div[2]/div[3]/div[2]/div/table/tbody/tr[4]/td[2]" #Washington

我正在尝试构建一个程序,当我运行程序时,它会抓取所有游戏并在各自的行上分别打印每个游戏:

Game1 away team Game1 home team
Game2 away team Game2 home team
Game3 away team Game3 home team

预期输出:

Arizona Coyotes Vegas Golden Knights
Chicago Blackhawks Washington Capitals
etc....

标签: pythonstringfor-loopselenium-chromedriver

解决方案


尝试这个 :

team_string = "//*[@id='teams_wrapper']/div[2]/div[3]/div[2]/div/table/tbody/tr[1]/td[2]"
all_team_list = [team_string[:65]+str(i+1)+team_string[66:] for i in range(0,15)] # Change 15 to 107/109
team_text = [driver.find_element_by_xpath(i).text for i in all_team_list]
team_text = zip(*[team_text[i::2] for i in range(2)])
print(*[f'Game {i+1} away team : {awt}, home team : {hmt}' for i, (awt, hmt) in enumerate(team_text)], sep='\n')

输出

Game 1 away team : Arizona Coyotes, home team : Vegas Golden Knights
Game 2 away team : Chicago Blackhawks, home team : Washington Capitals
Game 3 away team : Dallas Stars, home team : St Louis Blues
Game 4 away team : Boston Bruins, home team : New Jersey Devils
Game 5 away team : Calgary Flames, home team : Vancouver Canucks
Game 6 away team : Montreal Canadiens, home team : New Jersey Devils
Game 7 away team : New York Islanders, home team : Philadelphia Flyers

推荐阅读