Home Backend Development Python Tutorial 零基础写python爬虫之使用urllib2组件抓取网页内容

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

Jun 06, 2016 am 11:20 AM
python reptile

版本号: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 />
Copy after login


按下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 />
Copy after login

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

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

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

在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()  #读取反馈的内容
Copy after login

如果没有传送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) 
Copy after login

这样就实现了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()  
Copy after login

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

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

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

See all articles