如何在 python 中使用 selenium 从 class 名称中获取值?

How do I get a value from a class name using selenium in python?

我正在尝试从 class 名称中获取值,但现在唯一可以获取的是 [ ] 输出。 那么,我应该在以下代码中做什么?

from selenium import webdriver
import time

options = webdriver.ChromeOptions()
options.add_argument('lang=pt-br')
driver = webdriver.Chrome(
    executable_path=r'./chromedriver.exe', options=options)
driver.get('https://economia.uol.com.br/cotacoes/cambio/')
time.sleep(5)
dolar = driver.find_elements_by_class_name('currency2')
time.sleep(5)
print(dolar)

您可以使用 get_attribute 来检索 Web 元素的值,而且在您的代码中,您没有使用 class 名称 currency2 的元素。

请看下面的例子:

<input class="field normal" name="currency2" value="5,59" data-audience-click="{&quot;reference&quot;:&quot;ativar-campo-texto&quot;,&quot;component&quot;:&quot;currency-converter&quot;}" xpath="1">

检索值的代码:

driver.get('https://economia.uol.com.br/cotacoes/cambio/')
currency = driver.find_element_by_name('currency2')
print currency.get_attribute("value")

输出::

5,59

您不需要 selenium 来获取该信息,请尝试:

import requests

u = "https://api.cotacoes.uol.com/currency/intraday/list/?format=JSON&fields=bidvalue,askvalue,maxbid,minbid,variationbid,variationpercentbid,openbidvalue,date&currency=1"
j = requests.get(u).json()
dolar = j['docs'][0]['bidvalue']
# 5.5916

Demo


备注:

  • 如果您需要其他信息,例如每日变化 (variationpercentbid),请在 json 对象上搜索:

  • 将 url 末尾的货币值更改为不同的货币,例如 currency=5,将为您提供 EUR 值。