- [Instructor] One of the areas where Python really shines is in retrieving and working with data from the internet, such as jayson, xml, and html. In this chapter, we'll see how to work with all three. So let's begin by going into the chapter five folder and opening inetdata_start. In this first example, we're going to just retrieve data from a server and print the results. So in order to make a request to a web server, I need to import the url lib request module. So I'll so that first.
So this module provides the classes and code I need to make http requests. So now, let's define the main function. And then I'll create a variable named web url. And what I'm going to do is call the url open function on the request class, and that will give me back a response object. And url open just takes a string, represents the url. So I'll just go ahead and open up the Google home page. And for the moment, I'm just going to print out the result code.
The result code is obtained by calling the get code function on the web url response. And I have to cast that to a string, so this is going to be web url.get code. And this will just be a regular http result code, so example: 200 if everything is okay, 404 if the file's not found. Let's go ahead and save this and run what we've got so far. So I'll go to the debugger and open the output window.
And we'll run this and you can see that the result code is in fact 200. So I'm able to connect to the website without any errors. Now that we've got the url open, let's read some data and just print it out. To do that, I have to call the read function on this response. So I'm going to type data = and then web url.read. And then I'll just simply print the data. Recall from earlier in the course, we used a read function that allowed us to read the contents of local data files.
And I'm doing pretty much the same thing here, I'm just reading the entire contents of this url into a variable named data, and then it's going to print it out. So if all goes well, this should be the html code for Google's homepage. So let's save and let's go ahead and clear this output. And we'll run it again. And sure enough, you can see that it's working. This is the html that represents the Google.com homepage. So that's a quick introduction to how to read data from the internet.
And we'll see how to use this a little bit more in-depth as we go through the rest of the chapter and work with more structured data, such as jayson and xml.
- Installing Python
- Choosing an editor or IDE
- Working with variables and expressions
- Writing loops
- Using the date, time, and datetime classes
- Reading and writing files
- Fetching internet data
- Parsing and processing HTML