使用 Selenium 遍历列表

Iteration through a list using Selenium

我正在尝试从 html 中迭代有限数量的 <span> 个元素,这些元素实际上是从 webdriver 生成的列表。

我试过这样做:

for i in range(9):
    print(driver.find_element(By.CSS_SELECTOR, "thead > tr th:nth-child("+[i]+") > span").text)

我收到以下错误:

print(driver.find_element(By.CSS_SELECTOR, "tbody > tr td:nth-child("+[i]+") > span").text) TypeError: can only concatenate str (not "list") to str

这是 html 片段:

<thead><tr class="C($tertiaryColor) Fz(xs) Ta(end)"><th class="Ta(start) W(100px) Fw(400) Py(6px)"><span>Date</span></th><th class="Fw(400) Py(6px)"><span>Open</span></th><th class="Fw(400) Py(6px)"><span>High</span></th><th class="Fw(400) Py(6px)"><span>Low</span></th><th class="Fw(400) Py(6px)"><span>Close*</span></th><th class="Fw(400) Py(6px)"><span>Adj Close**</span></th><th class="Fw(400) Py(6px)"><span>Volume</span></th></tr></thead>

全部来自此页面:https://finance.yahoo.com/quote/BTC-EUR/history

to extract the text only from the first <span> which is a decendent of the first <th> and you are restricting the 中建议为:

driver.find_element(By.CSS_SELECTOR, "thead > tr th:nth-child(1) > span")

这个用例

遍历 website you can use and you can use the following 的 html 中的所有 <span> 元素:

driver.get('https://finance.yahoo.com/quote/BTC-EUR/history')
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "thead > tr th > span")))])

控制台输出:

['Date', 'Open', 'High', 'Low', 'Close*', 'Adj Close**', 'Volume', 'Symbol', 'Last Price', 'Change', '% Change']

要将 中的元素数量限制为 9 元素,您可以使用:

driver.get('https://finance.yahoo.com/quote/BTC-EUR/history')
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "thead > tr th > span")))][:9])