将所有选项标签更改为相同的值

Change all option tags to the same value

我正在尝试让所有轮次都相同,我能做的最好的就是改变第一个轮次。当前代码已打开所有玩家记分卡,现在我只需要能够 select 对所有玩家记分卡进行同一轮。

忽略所有导入我正在尝试一些东西,我对此非常陌生

谢谢!

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from bs4 import BeautifulSoup
import requests


PATH = "C:\Program Files (x86)\Chrome\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://www.espn.com/golf/leaderboard?tournamentId=401353233")

xpath_number = 1
while True:
    try:
        element = driver.find_element_by_xpath(f'//*[@id="fittPageContainer"]/div[3]/div/div/section[3]/div/div/div/div[2]/div[3]/div/div/div/div[2]/table/tbody/tr[{xpath_number}]/td[1]')
        xpath_number += 1
        action = ActionChains(driver)
        action.click(element)
        action.perform()
              
    except NoSuchElementException:
        break

此代码运行第一个循环以打开记分卡,然后运行第二个循环以更改回合。命令 .send_keys(Keys.DOWN * n) 其中 n 是一个整数,按向下箭头 n 次。

import time
from selenium.webdriver.common.keys import Keys

number_of_players = 10
round_to_select = 1

for idx,down_arrow in enumerate(driver.find_elements(By.CSS_SELECTOR, '.Table__TD:first-child')):
    if idx < number_of_players:
        down_arrow.click()
        time.sleep(.5)
    else:
        break

if round_to_select < 4:
    for idx,menu in enumerate(driver.find_elements(By.CSS_SELECTOR, '.competitors select[class=dropdown__select]')):
        if idx < number_of_players:
            menu.send_keys(Keys.DOWN * (4-round_to_select))
            time.sleep(.5)
        else:
            break

除了menu.send_keys(Keys.DOWN * (4-round_to_select)),我们还可以使用Select,如下所示

from selenium.webdriver.support.ui import Select

...

if round_to_select < 4:
    for idx,menu in enumerate(driver.find_elements(By.CSS_SELECTOR, '.competitors select[class=dropdown__select]')):
        if idx < number_of_players:
            Select(menu).select_by_visible_text(f'Round {round_to_select}')
            time.sleep(.5)
        else:
            break