python - 从 WebElement 获取文本

categories = driver.find_elements(By.XPATH, '//div[starts-with(@class, "item-1EEezFCx")]')

    for category in categories:
        try:
            text = driver.find_element(By.XPATH, '//div[@text()="{category.text}"').click()
            print(text)
            time.sleep(2)
        except ElementNotInteractableException:
            pass

在这里,我将 categories 作为 WebElements 的持有者,其类名均以 item-1EEezFCx 开头。对于每次迭代,我想访问 WebElement 的文本元素,打印并单击。请问您可以做什么来访问文本元素?

完整代码(已编辑):

import os
import time
import selenium.webdriver as webdriver
from selenium.webdriver.support.ui import  WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException, NoSuchElementException, ElementNotInteractableException
from bs4 import BeautifulSoup
import pandas as pd
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0'
path = "C:\\"

FireFoxDriverPath = os.path.join(path, 'Python39', 'geckodriver.exe')
FireFoxProfile = r'C:\Users\username\AppData\Roaming\Mozilla\Firefox\Profiles\ltk7fdt2.default'
options = Options()
options.set_preference('profile', FireFoxProfile)
service = Service(r'C:\Python39\geckodriver.exe')
driver = Firefox(service=service, options=options)

url = "https://www.tradingview.com/markets/cryptocurrencies/prices-all/"
driver.get(url)

# Step 1. Toggle the active currency
currency = 'USD'
active_currency = driver.find_element(By.XPATH, '//span[contains(@class, "modeTitleActive-bJ0BPoV3")]')

if active_currency.text == currency:
    pass
else:
    driver.find_element(By.XPATH, '//input[@type="checkbox")]').click()

# Step 2. Import tables
xlwriter = pd.ExcelWriter('TradingView Crypto Prices.xlsx')

categories = driver.find_elements(By.XPATH, '//div[starts-with(@class, "item-1EEezFCx")]')

# Load columns one by one
for category in categories:
    try:
        driver.find_element(By.XPATH, category).text()
        time.sleep(2)
    except ElementNotInteractableException:
        pass

    load_more = True
    while load_more:
        try:
            driver.find_element(By.CLASS_NAME, 'tv-load-more__btn').click()
            time.sleep(1)
        except ElementNotInteractableException:
            load_more = False

    df = pd.read_html(driver.page_source)[0]
    df.to_excel(xlwriter, sheet_name=category.text, index=False)

xlwriter.save()
driver.quit()

回答1

for category in categories:
    print(category.text)
    category.click()

相似文章

随机推荐

最新文章