用Python实现网络爬虫蜘蛛.docx

上传人:b****6 文档编号:8853296 上传时间:2023-02-02 格式:DOCX 页数:115 大小:247.66KB
下载 相关 举报
用Python实现网络爬虫蜘蛛.docx_第1页
第1页 / 共115页
用Python实现网络爬虫蜘蛛.docx_第2页
第2页 / 共115页
用Python实现网络爬虫蜘蛛.docx_第3页
第3页 / 共115页
用Python实现网络爬虫蜘蛛.docx_第4页
第4页 / 共115页
用Python实现网络爬虫蜘蛛.docx_第5页
第5页 / 共115页
点击查看更多>>
下载资源
资源描述

用Python实现网络爬虫蜘蛛.docx

《用Python实现网络爬虫蜘蛛.docx》由会员分享,可在线阅读,更多相关《用Python实现网络爬虫蜘蛛.docx(115页珍藏版)》请在冰豆网上搜索。

用Python实现网络爬虫蜘蛛.docx

用Python实现网络爬虫蜘蛛

python中如何提取网页正文啊谢谢

importurllib.request 

url="http:

//google./" 

response=urllib.request.urlopen(url) 

page=response.read() 

python提取网页中的文本

1.importos,sys,datetime   

2.importhttplib,urllib,re   

3.fromsgmllibimportSGMLParser   

4.  

5.importtypes   

6.  

7.classHtml2txt(SGMLParser):

   

8.    defreset(self):

   

9.        self.text=''  

10.        self.inbody=True  

11.        SGMLParser.reset(self)   

12.    defhandle_data(self,text):

   

13.        ifself.inbody:

   

14.            self.text+=text   

15.  

16.    defstart_head(self,text):

   

17.        self.inbody=False  

18.    defend_head(self):

   

19.        self.inbody=True  

20.  

21.  

22.if__name__=="__main__":

   

23.    parser=Html2txt()   

24.    parser.feed(urllib.urlopen("").read())   

25.    parser.close()   

26.    printparser.text.strip()  

python下载网页

importhttplib  

conn=httplib.HTTPConnection(".baidu.")

conn.request("GET","/index.html")

r1=conn.getresponse()

printr1.status,r1.reason

data=r1.read()

printdata

conn.close

用python下载网页,超级简单!

fromurllibimporturlopen

webdata=urlopen("").read()

printwebdata

深入python里面有

python 下载网页内容,用python的pycurl模块实现

1.用python下载网页内容还是很不错的,之前是使用urllib模块实验的,但听说有pycurl这个模块,而且比urllib好,所以尝试下,废话不说,以下是代码

2.

3.

4.#!

/usr/bin/envpython

5.#-*-coding:

utf-8-*-

6.importStringIO

7.importpycurl

8.

9.defwritefile(fstr,xfilename):

 f=open(xfilename,'w')

 f.write(fstr)

 f.close

10.

1.html=StringIO.StringIO()

2.c=pycurl.Curl()

3.myurl='http:

//.ppgchenshan.'

4. 

5.c.setopt(pycurl.URL,myurl)

6. 

7.#写的回调

8.c.setopt(pycurl.WRITEFUNCTION,html.write)

9. 

10.c.setopt(pycurl.FOLLOWLOCATION,1)

11. 

12.#最大重定向次数,可以预防重定向陷阱

13.c.setopt(pycurl.MAXREDIRS,5)

14. 

15.#连接超时设置

16.c.setopt(pycurl.CONNECTTIMEOUT,60)

17.c.setopt(pycurl.TIMEOUT,300)

18. 

19.#模拟浏览器

20.c.setopt(pycurl.USERAGENT,"Mozilla/4.0(patible;MSIE6.0;WindowsNT5.1;SV1;.NETCLR1.1.4322)")

21. 

22. 

23. 

24.#访问,阻塞到访问结束

25.c.perform()

26. 

27.#打印出200(HTTP状态码,可以不需要)

28.printc.getinfo(pycurl.HTTP_CODE)

29. 

30.#输出网页的内容

31.printhtml.getvalue()

32.#保存成down.txt文件

33.writefile(html.getvalue(),"down.txt")

python的pycurl模块的安装可以到

不同系统使用不同版本,自己看看

总结下,Python下载网页的几种方法

1

fd=urllib2.urlopen(url_link)

data=fd.read()

这是最简洁的一种,当然也是Get的方法

2

通过GET的方法

defGetHtmlSource(url):

try:

htmSource=''

req=urllib2.Request(url)

fd=urllib2.urlopen(req,"")

while1:

data=fd.read(1024)

ifnotlen(data):

break

htmSource+=data

fd.close()

delfd

delreq

htmSource=htmSource.decode('cp936')

htmSource=formatStr(htmSource)

returnhtmSource

exceptsocket.error,err:

str_err="%s"%err

return""

3

通过GET的方法

defGetHtmlSource_Get(htmurl):

htmSource=""

try:

urlx=httplib.urlsplit(htmurl)

conn=httplib.HTTPConnection(loc)

conn.connect()

conn.putrequest("GET",htmurl,None)

conn.putheader("Content-Length",0)

conn.putheader("Connection","close")

conn.endheaders()

res=conn.getresponse()

htmSource=res.read()

exceptException(),err:

trackback.print_exec()

conn.close()

returnhtmSource

通过POST的方法

defGetHtmlSource_Post(getString):

htmSource=""

try:

url=httplib.urlsplit("http:

//app.sipo.gov.:

8080")

conn=httplib.HTTPConnection(loc)

conn.connect()

conn.putrequest("POST","/sipo/zljs/hyjs-jieguo.jsp")

conn.putheader("Content-Length",len(getString))

conn.putheader("Content-Type","application/x--form-urlencoded")

conn.putheader("Connection","Keep-Alive")

conn.endheaders()

conn.send(getString)

f=conn.getresponse()

ifnotf:

raisesocket.error,"timedout"

htmSource=f.read()

f.close()

conn.close()

returnhtmSource

exceptException(),err:

trackback.print_exec()

conn.close()

returnhtmSource

本文来自CSDN博客,转载请标明出处:

Django+python+BeautifulSoup组合的垂直搜索爬虫

使用python+BeautifulSoup完成爬虫抓取特定数据的工作,并使用Django搭建一个管理平台,用来协调抓取工作。

因为自己很喜欢Djangoadmin后台,所以这次用这个后台对抓取到的链接进行管理,使我的爬虫可以应对各种后期的需求。

比如分时段抓取,定期的对已经抓取的地址重新抓取。

数据库是用python自带的sqlite3,所以很方便。

这几天正好在做一个电影推荐系统,需要些电影数据。

本文的例子是对豆瓣电影抓取特定的数据。

第一步:

建立Django模型

模仿nutch的爬虫思路,这里简化了。

每次抓取任务开始先从数据库里找到未保存的(is_save=False)的链接,放到抓取链表里。

你也可以根据自己的需求去过滤链接。

python代码:

viewplaincopytoclipboardprint?

01.classCrawl_URL(models.Model):

02.url=models.URLField('抓取地址',max_length=100,unique=True)

03.weight=models.SmallIntegerField('抓取深度',default=0)#抓取深度起始1

04.is_save=models.BooleanField('是否已保存',default=False)#

05.date=models.DateTimeField('保存时间',auto_now_add=True,blank=True,null=True)

06.def__unicode__(self):

07.returnself.url

classCrawl_URL(models.Model):

url=models.URLField('抓取地址',max_length=100,unique=True)

weight=models.SmallIntegerField('抓取深度',default=0)#抓取深度起始1

is_save=models.BooleanField('是否已保存',default=False)#

date=models.DateTimeField('保存时间',auto_now_add=True,blank=True,null=True)

def__unicode__(self):

returnself.url

然后生成相应的表。

还需要一个admin管理后台

viewplaincopytoclipboardprint?

01.classCrawl_URLAdmin(admin.ModelAdmin):

02.list_display=('url','weight','is_save','date',)

03.ordering=('-id',)

04.list_filter=('is_save','weight','date',)

05.fields=('url','weight','is_save',)

06.admin.site.register(Crawl_URL,Crawl_URLAdmin)

classCrawl_URLAdmin(admin.ModelAdmin):

list_display=('url','weight','is_save','date',)

ordering=('-id',)

list_filter=('is_save','weight','date',)

fields=('url','weight','is_save',)

admin.site.register(Crawl_URL,Crawl_URLAdmin)

第二步,编写爬虫代码

爬虫是单线程,并且每次抓取后都有相应的暂定,豆瓣网会禁止一定强度抓取的爬虫

爬虫根据深度来控制,每次都是先生成链接,然后抓取,并解析出更多的链接,最后将抓取过的链接is_save=true,并把新链接存入数据库中。

每次一个深度抓取完后都需要花比较长的时候把链接导入数据库。

因为需要判断链接是否已存入数据库。

这个只对满足正则表达式http:

//movie.douban./subject/(\d+)/的地址进行数据解析。

并且直接忽略掉不是电影模块的链接。

第一次抓取需要在后台加个链接,比如http:

//movie.douban./chart,这是个排行榜的页面,电影比较受欢迎。

python代码:

#这段代码不能格式化发

#coding=UTF-8

importurllib2

fromBeautifulSoupimport*

fromurlparseimporturljoin

frompysqlite2importdbapi2assqlite

frommovie.modelsimport*

fromdjango.contrib.auth.modelsimportUser

fromtimeimportsleep

image_path='C:

/Users/soul/djcodetest/picture/'

user=User.objects.get(id=1)

defcrawl(depth=10):

foriinrange(1,depth):

print'开始抓取for%d....'%i

pages=Crawl_URL.objects.filter(is_save=False)

newurls={}

forcrawl_pageinpages:

page=crawl_page.url

try:

c=urllib2.urlopen(page)

except:

continue

try:

#解析元数据和url

soup=BeautifulSoup(c.read())

#解析电影页面

ifre.search(r'^http:

//movie.douban./subject/(\d+)/$',page):

read_html(soup)

#解析出有效的链接,放入newurls

links=soup('a')

forlinkinlinks:

if'href'indict(link.attrs):

url=urljoin(page,link['href'])

ifurl.find("'")!

=-1:

continue

iflen(url)>60:

continue

url=url.split('#')[0]#removielocationportion

ifre.search(r'^http:

//movie.douban.',url):

newurls[url]=crawl_page.weight+1#连接有效。

存入字典中

try:

print'addurl:

'

except:

pass

exceptException.args:

try:

print"Couldnotparse:

%s"%args

except:

pass

#newurls存入数据库is_save=Falseweight=i

crawl_page.is_save=True

crawl_page.save()

#休眠2.5秒

sleep(2.5)

save_url(newurls)

#保存url,放到数据库里

defsave_url(newurls):

for(url,weight)innewurls.items():

url=Crawl_URL(url=url,weight=weight)

try:

url.save()

except:

try:

print'url重复:

'

except:

pass

returnTrue

第三步,用BeautifulSoup解析页面

抽取出电影标题,图片,剧情介绍,主演,标签,地区。

关于BeautifulSoup的使用可以看这里BeautifulSoup技术文档

viewplaincopytoclipboardprint?

01.#抓取数据02.defread_html(soup):

03.#解析出标题04.html_title=soup.html.head.title.string05.title=html_title[:

len(html_title)-5]06.#解析出电影介绍07.try:

08.intro=soup.find('span',attrs={'class':

'allhidden'}).text09.except:

10.try:

11.node=soup.find('div',attrs={'class':

'blank20'}).previousSibling12.intro=node.contents[0]+node.contents[2]13.except:

14.try:

15.contents=soup.find('div',attrs={'class':

'blank20'}).previousSibling.previousSibling.text16.intro=contents[:

len(contents)-22]17.except:

18.intro=u'暂无'19.20.#取得图片21.html_image=soup('a',href=re.pile('douban./lpic'))[0]['href']22.data=urllib2.urlopen(html_image).read()23.image='201003/'+html_image[html_image.rfind('/')+1:

]24.f=file(image_path+image,'wb')25.f.write(data)26.f.close()27.28.29.#解析出地区30.try:

31.soup_obmo=soup.find('div',attrs={'class':

'obmo'}).findAll('span')32.html_area=soup_obmo[0].nextSibling.split('/')33.area=html_area[0].lstrip()34.except:

35.area=''36.37.#time=soup_obmo[1].nextSibling.split('')[1]38.#time=time.strptime(html_time,'%Y-%m-%d')39.40.#生成电影对象41.new_movie=Movie(title=title,intro=intro,area=area,version='暂无',upload_user=user,image=image)42.new_movie.save()43.try:

44.actors=soup.find('div',attrs={'id':

'info'}).findAll('span')[5].nextSibling.nextSibling.string.split('')[0]45.actors_list=Actor.objects.filter(name=actors)46.iflen(actors_list)==1:

47.actor=actors_list[0]48.new_movie.actors.add(actor)49.else:

50.actor=Actor(name=actors)51.actor.save()52.new_movie.actors.add(actor)53.except:

54.pass55.56.#tag57.tags=soup.find('div',attrs={'class':

'blank20'}).findAll('a')58.fortag_htmlintags:

59.tag_str=tag_html.string60.iflen(tag_str)>4:

61.continue62.tag_list=Tag.objects.filter(name=tag_str)63.iflen(tag_list)==1:

64.tag=tag_list[0]65.66.new_movie.tags.add(tag)67.else:

68.tag=Tag(name=tag_str)69.tag.save()70.new_movie.tags.add(tag)71.#try:

72.73.#exceptException.args:

74.#print"Couldnotdownload:

%s"%args75.printr'downloadsuccess'76.#抓取数据

defr

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 党团工作 > 入党转正申请

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1