import network
import urequests # MicroPython版的requests库
from machine import I2C, Pin
from ssd1306 import SSD1306_I2C
import re # 使用正则表达式解析HTML
# 连接到Wi-Fi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('Wokwi-GUEST', '')
# 等待连接
while not wlan.isconnected():
pass
print('网络配置:', wlan.ifconfig())
# 金价的URL
gold_price_url = 'https://www.huangjinjiage.com/' # 替换为实际的URL
def get_gold_price(url):
try:
# 发送GET请求
response = urequests.get(url)
match = re.search(r'class="value-box die">([0-9,.]+)<i>元/克</i></div>', response.text)
if match:
return match.group(1).strip() # 返回提取的金价文本
else:
return "金价信息未找到"
except Exception as e:
return f"请求或解析错误: {str(e)}"
# 初始化I2C和OLED显示
i2c = I2C(scl=Pin(22), sda=Pin(21))
oled = SSD1306_I2C(128, 64, i2c)
# 调用函数并打印结果
gold_price = get_gold_price(gold_price_url)
print(gold_price)
# 在OLED上显示金价
oled.fill(0) # 清空显示
oled.text("gold price:", 0, 0)
oled.text(gold_price, 0, 10)
oled.show()