前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python实例代码爬虫_python 网络爬虫实例代码

python实例代码爬虫_python 网络爬虫实例代码

作者头像
全栈程序员站长
发布2022-11-15 11:25:14
1.3K0
发布2022-11-15 11:25:14
举报
文章被收录于专栏:全栈程序员必看

本节内容:

python 网络爬虫代码。

一共两个文件,一个是toolbox_insight.py,是一个工具文件另一个是test.py,是一个用到toolbox_insight.py中工具的测试文件 代码示例:

#filename: toolbox_insight.py

from sgmllib import sgmlparser

import threading

import time

import urllib2

import stringio

import gzip

import string

import os

#rewrite sgmlparser for start_a

class basegeturls(sgmlparser): #这个basegeturls类作用是分析下载的网页,把网页中的所有链接放在self.url中。

def reset(self):

self.url = []

sgmlparser.reset(self)

def start_a(self, attrs):

href = [v for k, v in attrs if k == ‘href’]

if href:

self.url.extend(href)

#for quickly finding

class newlist(list):#这个类其实是一个添加了find方法的list。当num变量在list中,返回true,当不在list中,返回false并把num按二分法插入list中

def find(self, num):

l = len(self)

first = 0

end = l – 1

mid = 0

if l == 0:

self.insert(0,num)

return false

while first < end:

mid = (first + end)/2

if num > self[mid]:

first = mid + 1

elif num < self[mid]:

end = mid – 1

else:

break

if first == end:

if self[first] > num:

self.insert(first, num)

return false

elif self[first] < num:

self.insert(first + 1, num)

return false

else:

return true

elif first > end:

self.insert(first, num)

return false

else:

return true

#下面的reptile顾名思义是一个爬虫

class reptile(threading.thread):

#name: 是爬虫是名字,queue是任务队列,所有的爬虫共用同一个任务队列

#从中取出一个任务项进行运行,每个任务项是一个要下载网页的url

#result: 也是一个队列,将下载的网页中包含的url放入该队列中

#inittime: 在本程序中没有用,只是一个为了以后扩展用的

#downloadway:是下载的网页存放的路径

#configfile: 是配置文件,存放网页的url和下载下后的路径

#maxnum: 每个爬虫有个最大下载量,当下载了这么多网页后,爬虫dead

def __init__(self, name, queue, result, flcok, inittime = 0.00001, downloadway = ‘d:\\bbs\\’,configfile = ‘d:\\bbs\\conf.txt’, maxnum = 10000):

threading.thread.__init__(self, name = name)

self.queue = queue

self.result = result

self.flcok = flcok

self.inittime = inittime

self.mainway = downloadway

self.configfile = configfile

self.num = 0 #已下载的网页个数

self.maxnum = maxnum

os.makedirs(downloadway + self.getname()) #系统调用:在存放网页的文件夹中创建一个以该爬虫name为名字的文件夹

self.way = downloadway + self.getname() + ‘\\’

def run(self):

opener = urllib2.build_opener() #创建一个开启器

while true:

url = self.queue.get() #从队列中取一个url

if url == none: #当取得一个none后表示爬虫结束工作,用于外部方便控制爬虫的生命期

break

parser = basegeturls() #创建一个网页分析器

request = urllib2.request(url) #网页请求

request.add_header(‘accept-encoding’, ‘gzip’)#下载的方式是gzip压缩后的网页,gzip是大多数服务器支持的一种格式

try: #这样可以减轻网络压力

page = opener.open(request)#发送请求报文

if page.code == 200: #当请求成功

predata = page.read() #下载gzip格式的网页

pdata = stringio.stringio(predata)#下面6行是实现解压缩

gzipper = gzip.gzipfile(fileobj = pdata)

try:

data = gzipper.read()

except(ioerror):

print ‘unused gzip’

data = predata#当有的服务器不支持gzip格式,那么下载的就是网页本身

try:

parser.feed(data)#分析网页

except:

print ‘i am here’#有的网页分析不了,如整个网页就是一个图片

for item in parser.url:

self.result.put(item)#分析后的url放入队列中

way = self.way + str(self.num) + ‘.html’#下面的是网页的保存,不多说了

self.num += 1

file = open(way, ‘w’)

file.write(data)

file.close()

self.flcok.acquire()

confile = open(self.configfile, ‘a’)

confile.write( way + ‘ ‘ + url + ‘\n’)

confile.close()

self.flcok.release()

page.close()

if self.num >= self.maxnum:#达到最大量后退出

break

except:

print ‘end error’

#和爬虫一样是个线程类,作用是将爬虫中的result中存入的url加以处理。只要同一个服务器的网页

class proinsight(threading.thread):

def __init__(self, queue, list, homepage, inqueue):

threading.thread.__init__(self)

self.queue = queue#和爬虫中的result队列是同一个

self.list = list#是上面newlist的对象

self.homepage = homepage#主页

self.inqueue = inqueue#处理完后的url的去处

def run(self):

length = len(self.homepage)

while true:

item = self.queue.get()

if item == none:

break

if item[0:4] == ‘\r\n’:

item = item[4:]

if item[-1] == ‘/’:

item = item[:-1]

if len(item) >= len(‘http://’) and item[0:7] == ‘http://’:

if len(item) >= length and item[0:length] == self.homepage:

if self.list.find(item) == false:

self.inqueue.put(item)

elif item[0:5] == ‘/java’ or item[0:4] == ‘java’:

pass

else:

if item[0] != ‘/’:

item = ‘/’ + item

item = self.homepage + item

if self.list.find(item) == false:

self.inqueue.put(item)

主函数过程

我下载的网站是http://bbs.hit.edu.cn

开始网页是http://bbs.hit.edu.cn/mainpage.php 代码示例:

#filename:test

from toolbox_insight import *

from queue import queue

import threading

import sys

num = int(raw_input(‘enter the number of thread:’))

pnum = int(raw_input(‘enter the number of download pages:’))

mainpage = str(raw_input(‘the mainpage:’))

startpage = str(raw_input(‘start page:’))

queue = queue()

key = queue()

inqueue = queue()

list = newlist()

thlist = []

flock = threading.rlock()

for i in range(num):

th = reptile(‘th’ + str(i), queue, key, flock)

thlist.append(th)

pro = proinsight(key, list, mainpage, inqueue)

pro.start()

for i in thlist:

i.start()

queue.put(startpage)

for i in range(pnum):

queue.put(inqueue.get())

for i in range(num):

queue.put(none)

个人觉得用wxpython来实现用户界面和用数据库知识查找url是更好的扩展方向。

python网络爬虫采集联想词实例

python博客文章爬虫实现代码

python网页爬虫程序示例代码

python 网络爬虫(经典实用型)

Python 网易新闻小爬虫的实现代码

python网络爬虫的代码

python 实现从百度开始不断搜索的爬虫

Python实现天气预报采集器(网页爬虫)的教程

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/234970.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年11月1日 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档