Raspberry Pi Pico W
Reading Web Page Content

Once you have checked that you can connect to the Internet, we might want to grab some content from a web page.

The following program depends on having a secrets.py file with your SSID and password defined. It visits Adafruit's WiFi test page.

from time import sleep
from network import WLAN, STA_IF
from secrets import secrets
from urequests import get

wlan = WLAN(STA_IF)

def connect():
    wlan.active(True)
    wlan.config(pm = 0xa11140)
    wlan.connect(secrets["ssid"], secrets["password"])

    # try to connect or fail
    max_wait = 10
    while max_wait >0:
        if wlan.status() <0 or wlan.status()>=3:
            break
        max_wait -= 1
        print("Waiting for connection...")
        sleep(1)

    # connection error
    if wlan.status() != 3:
        return False
    else:
        status = wlan.ifconfig()
        print("Connected to", secrets["ssid"], "on", status[0])
        print()
        return True

if not connect():
    print("Couldn't connect to WiFi.")
else:
    print("Success.")
    print()
    TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
    print("Fetching text from", TEXT_URL)
    r = get(TEXT_URL)
    print("-"*40)
    print(r.content.decode("utf-8"))
    print("-"*40)
    r.close()
    wlan.disconnect()
    print("Disconnected.")

To get the contents of the page, you need to import the urequests module - or at least import the get function from it. With that done, the rest of the work is taking place right at the end of the program.

Adafruit's test page is simply a text file, albeit with an HTML file extensions. The r.content.decode('utf-8') statement will return a string of the page's HTML. You can then hunt down the key parts of the page with some nice string handling.