🎓 A1Learner
🔍
0 of 52 lessons completed

Python Fetching Text From the Web

Fetching text from the web means asking a web address for its words. urlopen() fetches those words, and read() brings them back as bytes.

Fetch returns bytes

urlopen() fetches the words at the address. read() brings them back as bytes.

from urllib.request import urlopen
reply = urlopen('data:text/plain,Python%20is%20fun.')
print(reply.read())

Decode turns bytes into text

decode() turns bytes into plain text. The text prints without the b mark.

from urllib.request import urlopen
reply = urlopen('data:text/plain,Python%20is%20fun.')
print(reply.read().decode())

Fetch a file the program just wrote

open() writes a small file first. urlopen() then fetches it back with a file address.

from urllib.request import urlopen
with open("page.html", "w") as f:
    f.write("<p>Python is fun.</p>")
reply = urlopen("file:page.html")
print(reply.read().decode())

Example

from urllib.request import urlopen
html = "<html><body><p>Python is fun.</p></body></html>"
with open("page.html", "w") as f:
    f.write(html)
reply = urlopen("file:page.html")
text = reply.read().decode()
print(text)
print(len(text))

Key points

  • urlopen(): a function that asks a web address for its words
  • Use urlopen(address) to fetch the words at that address
  • read(): a method that brings back the fetched words as bytes
  • Bytes: raw data that print() shows with a b mark in front
  • Use decode() to turn bytes into plain text
  • The same call fetches a real page on your own computer.
  • A data address carries its own words, like data:text/plain,Python%20is%20fun.
  • A file address fetches a file on the computer, like file:page.html

In this example, the program builds a small web page as text. open() writes that text into a file named page.html. urlopen() then fetches the file back with a file address. read() brings the file words back as bytes. decode() turns those bytes into plain text. The first printout shows the whole page. The second printout shows its length, 47.

Note

The runner here has no network, so this lesson fetches from data the page itself carries.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does reply.read() give back?