Home > Backend Development > Python Tutorial > Detailed explanation of the solution to urlopen error in python3 urllib

Detailed explanation of the solution to urlopen error in python3 urllib

高洛峰
Release: 2017-03-28 09:44:59
Original
2787 people have browsed it

This article mainly introduces how to solve the problem of urlopen error in python3 urllib The relevant information is introduced in great detail. I believe it will be of certain reference value to everyone. Friends who need it can take a look below.

Preface

I recently updated the Python version and was going to write a crawler. I unexpectedly found that the attribute urlopen did not exist in the urllib library, so I googled it and summarized the solution.

The occurrence of the problem

详解python3 urllib中urlopen报错的解决方法

AttributeError: 'module' object has no attribute 'urlopen '

Solution to the problem

Let's first look at the explanation of the official document:

a new urllib package was created. It consists of code from 
urllib, urllib2, urlparse, and robotparser. The old 
modules have all been removed. The new package has five submodules: 
urllib.parse, urllib.request, urllib.response, 
urllib.error, and urllib.robotparser. The 
urllib.request.urlopen() function uses the url opener from 
urllib2. (Note that the unittests have not been renamed for the 
beta, but they will be renamed in the future.)
Copy after login

That is to say, the official version 3.0 has integrated urllib2, urlparse and other five modules into urllib, that is, integrated.

Correct usage

import urllib.request 
url="http://www.baidu.com" 
get=urllib.request.urlopen(url).read() 
print(get)
Copy after login

Result diagram:

详解python3 urllib中urlopen报错的解决方法

In fact, you can also change the utf-8 encoding to read the source code More correct, but this is no longer mentioned in the extra chapter.

The above is the detailed content of Detailed explanation of the solution to urlopen error in python3 urllib. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template