搜尋
首頁後端開發Python教學python 网络爬虫初级实现代码

首先,我们来看一个Python抓取网页的库:urllib或urllib2。

那么urllib与urllib2有什么区别呢?
可以把urllib2当作urllib的扩增,比较明显的优势是urllib2.urlopen()可以接受Request对象作为参数,从而可以控制HTTP Request的header部。
做HTTP Request时应当尽量使用urllib2库,但是urllib.urlretrieve()函数以及urllib.quote等一系列quote和unquote功能没有被加入urllib2中,因此有时也需要urllib的辅助。

urllib.open()这里传入的参数要遵循一些协议,比如http,ftp,file等。例如:

urllib.open('http://www.baidu.com')
urllib.open('file:D\Python\Hello.py')

现在有一个例子,下载一个网站上所有gif格式的图片。那么Python代码如下:

import re
import urllib

def getHtml(url):
 page = urllib.urlopen(url)
 html = page.read()
 return html

def getImg(html):
 reg = r'src="(.*?\.gif)"'
 imgre = re.compile(reg)
 imgList = re.findall(imgre,html)
 print imgList
 cnt = 1
 for imgurl in imgList:
  urllib.urlretrieve(imgurl,'%s.jpg' %cnt)
  cnt += 1

if __name__ == '__main__':
 html = getHtml('http://www.baidu.com')
 getImg(html)

根据上面的方法,我们可以抓取一定的网页,然后提取我们所需要的数据。

实际上,我们利用urllib这个模块来做网络爬虫效率是极其低下的,下面我们来介绍Tornado Web Server。
Tornado web server是使用Python编写出来的一个极轻量级、高可伸缩性和非阻塞IO的Web服务器软件,著名的Friendfeed网站就是使用它搭建的。Tornado跟其他主流的Web服务器框架(主要是Python框架)不同是采用epoll非阻塞IO,响应快速,可处理数千并发连接,特别适用用于实时的Web服务。

用Tornado Web Server来抓取网页效率会比较高。
从Tornado的官网来看,还要安装backports.ssl_match_hostname,官网如下:

http://www.tornadoweb.org/en/stable/

import tornado.httpclient

def Fetch(url):
 http_header = {'User-Agent' : 'Chrome'}
 http_request = tornado.httpclient.HTTPRequest(url=url,method='GET',headers=http_header,connect_timeout=200,request_timeout=600)
 print 'Hello'
 http_client = tornado.httpclient.HTTPClient()
 print 'Hello World'

 print 'Start downloading data...'
 http_response = http_client.fetch(http_request)
 print 'Finish downloading data...'

 print http_response.code

 all_fields = http_response.headers.get_all()
 for field in all_fields:
  print field

 print http_response.body

if __name__ == '__main__':
 Fetch('http://www.baidu.com')

urllib2的常见方法:

(1)info() 获取网页的Header信息

(2)getcode() 获取网页的状态码

(3)geturl() 获取传入的网址

(4)read() 读取文件的内容

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解釋嗎?揭穿神話Python:它是真正的解釋嗎?揭穿神話May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

與同一元素的Python串聯列表與同一元素的Python串聯列表May 11, 2025 am 12:08 AM

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

解釋與編譯語言:Python的位置解釋與編譯語言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循環時:您什麼時候在Python中使用?循環時:您什麼時候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。