python - 在 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....
解决方案
尝试这个 :
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
推荐阅读
- sharepoint - 通过 REST API 将 SharePoint 文件 URL 添加到 QnA 制造商不起作用
- javascript - 有没有办法将状态信息从反应钩子传递到反应中的嵌套函数?
- ruby - 有没有办法在 Ruby 中获得 HTTPClient 错误响应?
- angular - 在 Angular 中显示 FormControl 的值
- r - 使用闪亮的交互式条形图 - 基于选定列的图形更改
- google-colaboratory - 无法增加谷歌合作的RAM
- .net - 如何将 Kafka Transactional Producer 与具有多个模式记录的模式注册表一起使用?
- python - 如何从字符串行中拆分整数?
- graphql - GraphQL 中的空白是否重要?
- r - 使用 R 计算使用 mi.meld 的 amelia 插补的均值和方差(完整的 r 新手)