search
HomeBackend DevelopmentPython Tutorial零基础写python爬虫之使用urllib2组件抓取网页内容

版本号:Python2.7.5,Python3改动较大,各位另寻教程。

所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地。 
类似于使用程序模拟IE浏览器的功能,把URL作为HTTP请求的内容发送到服务器端, 然后读取服务器端的响应资源。

在Python中,我们使用urllib2这个组件来抓取网页。
urllib2是Python的一个获取URLs(Uniform Resource Locators)的组件。

它以urlopen函数的形式提供了一个非常简单的接口。

最简单的urllib2的应用代码只需要四行。

我们新建一个文件urllib2_test01.py来感受一下urllib2的作用:

import urllib2<br />response = urllib2.urlopen('http://www.baidu.com/')<br />html = response.read()<br />print html<br />


按下F5可以看到运行的结果:


我们可以打开百度主页,右击,选择查看源代码(火狐OR谷歌浏览器均可),会发现也是完全一样的内容。

也就是说,上面这四行代码将我们访问百度时浏览器收到的代码们全部打印了出来。

这就是一个最简单的urllib2的例子。

除了"http:",URL同样可以使用"ftp:","file:"等等来替代。

HTTP是基于请求和应答机制的:

客户端提出请求,服务端提供应答。

urllib2用一个Request对象来映射你提出的HTTP请求。

在它最简单的使用形式中你将用你要请求的地址创建一个Request对象,

通过调用urlopen并传入Request对象,将返回一个相关请求response对象,

这个应答对象如同一个文件对象,所以你可以在Response中调用.read()。

我们新建一个文件urllib2_test02.py来感受一下:

import urllib2  <br />req = urllib2.Request('http://www.baidu.com')  <br />response = urllib2.urlopen(req)  <br />the_page = response.read()  <br />print the_page<br />

可以看到输出的内容和test01是一样的。

urllib2使用相同的接口处理所有的URL头。例如你可以像下面那样创建一个ftp请求。

req = urllib2.Request('ftp://example.com/')

在HTTP请求时,允许你做额外的两件事。

1.发送data表单数据

这个内容相信做过Web端的都不会陌生,

有时候你希望发送一些数据到URL(通常URL与CGI[通用网关接口]脚本,或其他WEB应用程序挂接)。

在HTTP中,这个经常使用熟知的POST请求发送。

这个通常在你提交一个HTML表单时由你的浏览器来做。

并不是所有的POSTs都来源于表单,你能够使用POST提交任意的数据到你自己的程序。

一般的HTML表单,data需要编码成标准形式。然后做为data参数传到Request对象。

编码工作使用urllib的函数而非urllib2。

我们新建一个文件urllib2_test03.py来感受一下:

import urllib  <br />import urllib2  <br />url = 'http://www.someserver.com/register.cgi'  <br />values = {'name' : 'WHY',  <br />          'location' : 'SDU',  <br />          'language' : 'Python' }  <br />data = urllib.urlencode(values) # 编码工作<br />req = urllib2.Request(url, data)  # 发送请求同时传data表单<br />response = urllib2.urlopen(req)  #接受反馈的信息<br />the_page = response.read()  #读取反馈的内容

如果没有传送data参数,urllib2使用GET方式的请求。

GET和POST请求的不同之处是POST请求通常有"副作用",

它们会由于某种途径改变系统状态(例如提交成堆垃圾到你的门口)。

Data同样可以通过在Get请求的URL本身上面编码来传送。

import urllib2  <br />import urllib<br />data = {}<br />data['name'] = 'WHY'  <br />data['location'] = 'SDU'  <br />data['language'] = 'Python'<br />url_values = urllib.urlencode(data)  <br />print url_values<br />name=Somebody+Here&language=Python&location=Northampton  <br />url = 'http://www.example.com/example.cgi'  <br />full_url = url + '&#63;' + url_values<br />data = urllib2.open(full_url) 

这样就实现了Data数据的Get传送。

2.设置Headers到http请求

有一些站点不喜欢被程序(非人为访问)访问,或者发送不同版本的内容到不同的浏览器。

默认的urllib2把自己作为“Python-urllib/x.y”(x和y是Python主版本和次版本号,例如Python-urllib/2.7),

这个身份可能会让站点迷惑,或者干脆不工作。

浏览器确认自己身份是通过User-Agent头,当你创建了一个请求对象,你可以给他一个包含头数据的字典。

下面的例子发送跟上面一样的内容,但把自身模拟成Internet Explorer。

(多谢大家的提醒,现在这个Demo已经不可用了,不过原理还是那样的)。

import urllib  <br />import urllib2  <br />url = 'http://www.someserver.com/cgi-bin/register.cgi'<br />user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'  <br />values = {'name' : 'WHY',  <br />          'location' : 'SDU',  <br />          'language' : 'Python' }  <br />headers = { 'User-Agent' : user_agent }  <br />data = urllib.urlencode(values)  <br />req = urllib2.Request(url, data, headers)  <br />response = urllib2.urlopen(req)  <br />the_page = response.read()  

以上就是python利用urllib2通过指定的URL抓取网页内容的全部内容,非常简单吧,希望对大家能有所帮助

Statement
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
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software