请教一道 Pythonpython3 多线程爬虫虫的面试题

Python 爬虫学习笔记之单线程爬虫
作者:千里追风
字体:[ ] 类型:转载 时间:
本文给大家分享的是python使用requests爬虫库实现单线程爬虫的代码以及requests库的安装和使用,有需要的小伙伴可以参考下
本篇文章主要介绍如何爬取麦子学院的课程信息(本爬虫仍是单线程爬虫),在开始介绍之前,先来看看结果示意图
怎么样,是不是已经跃跃欲试了?首先让我们打开麦子学院的网址,然后找到麦子学院的全部课程信息,像下面这样
这个时候进行翻页,观看网址的变化,首先,第一页的网址是 /course/list/, 第二页变成了 /course/list/all-all/0-2/, 第三页变成了 /course/list/all-all/0-3/ ,可以看到,每次翻一页,0后面的数字就会递增1,然后就有人会想到了,拿第一页呢?我们尝试着将 /course/list/all-all/0-1/ 放进浏览器的地址栏,发现可以打开第一栏,那就好办了,我们只需要使用 re.sub() 就可以很轻松的获取到任何一页的内容。获取到网址链接之后,下面要做的就是获取网页的源代码,首先右击查看审查或者是检查元素,就可以看到以下界面
找到课程所在的位置以后,就可以很轻松的利用正则表达式将我们需要的内容提取出来,至于怎么提取,那就要靠你自己了,尝试着自己去找规律才能有更大的收获。如果你实在不知道怎么提取,那么继续往下,看我的源代码吧
实战源代码
# coding=utf-8
import requests
import sys
reload(sys)
sys.setdefaultencoding("utf8")
class spider():
def __init__(self):
print "开始爬取内容。。。"
def changePage(self, url, total_page):
nowpage = int(re.search('/0-(\d+)/', url, re.S).group(1))
pagegroup = []
for i in range(nowpage, total_page + 1):
link = re.sub('/0-(\d+)/', '/0-%s/' % i, url, re.S)
pagegroup.append(link)
return pagegroup
def getsource(self, url):
html = requests.get(url)
return html.text
def getclasses(self, source):
classes = re.search('&ul class="zy_course_list"&(.*?)&/ul&', source, re.S).group(1)
return classes
def geteach(self, classes):
eachclasses = re.findall('&li&(.*?)&/li&', classes, re.S)
return eachclasses
def getinfo(self, eachclass):
info['title'] = re.search('&a title="(.*?)"', eachclass, re.S).group(1)
info['people'] = re.search('&p class="color99"&(.*?)&/p&', eachclass, re.S).group(1)
return info
def saveinfo(self, classinfo):
f = open('info.txt', 'a')
for each in classinfo:
f.writelines('title : ' + each['title'] + '\n')
f.writelines('people : ' + each['people'] + '\n\n')
if __name__ == '__main__':
classinfo = []
url = '/course/list/all-all/0-1/'
maizispider = spider()
all_links = maizispider.changePage(url, 30)
for each in all_links:
htmlsources = maizispider.getsource(each)
classes = maizispider.getclasses(htmlsources)
eachclasses = maizispider.geteach(classes)
for each in eachclasses:
info = maizispider.getinfo(each)
classinfo.append(info)
maizispider.saveinfo(classinfo)
以上代码并不难懂,基本就是正则表达式的使用,然后直接运行就可以看到开头我们的截图内容了,由于这是单线程爬虫,所以运行速度感觉有点慢,接下来还会继续更新多线程爬虫。
应小伙伴们的要求,下面附上requests爬虫库的安装和简单示例
首先安装pip包管理工具,下载get-pip.py. 我的机器上安装的既有python2也有python3。
安装pip到python2:
python get-pip.py
安装到python3:
python3 get-pip.py
pip安装完成以后,安装requests库开启python爬虫学习。
安装requests
pip3 install requests
我使用的python3,python2可以直接用pip install requests.
import requests
html=requests.get("http://gupowang./article/283878")
html.encoding='utf-8'
print(html.text)
第一行引入requests库,第二行使用requests的get方法获取网页源代码,第三行设置编码格式,第四行文本输出。
把获取到的网页源代码保存到文本文件中:
import requests
html=requests.get("http://gupowang./article/283878")
html_file=open("news.txt","w")
html.encoding='utf-8'
print(html.text,file=html_file)
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具python多线程多队列(BeautifulSoup网络爬虫)
程序大概内容如下:
程序中设置两个队列分别为queue负责存放网址,out_queue负责存放网页的源代码。
ThreadUrl线程负责将队列queue中网址的源代码urlopen,存放到out_queue队列中。
DatamineThread线程负责使用BeautifulSoup模块从out_queue网页的源代码中提取出想要的内容并输出。
这只是一个基本的框架,可以根据需求继续扩展。
程序中有很详细的注释,如有有问题跪求指正啊。
import Queue
import threading
import urllib2
import time
from BeautifulSoup import BeautifulSoup
hosts = [&&,&&,&&,
queue = Queue.Queue()#存放网址的队列
out_queue = Queue.Queue()#存放网址页面的队列
class ThreadUrl(threading.Thread):
def __init__(self,queue,out_queue):
threading.Thread.__init__(self)
self.queue = queue
self.out_queue = out_queue
def run(self):
while True:
host = self.queue.get()
url = urllib2.urlopen(host)
chunk = url.read()
self.out_queue.put(chunk)#将hosts中的页面传给out_queue
self.queue.task_done()#传入一个相当于完成一个任务
class DatamineThread(threading.Thread):
def __init__(self,out_queue):
threading.Thread.__init__(self)
self.out_queue = out_queue
def run(self):
while True:
chunk = self.out_queue.get()
soup = BeautifulSoup(chunk)#从源代码中搜索title标签的内容
print soup.findAll(['title'])
self.out_queue.task_done()
start = time.time()
def main():
for i in range(5):
t = ThreadUrl(queue,out_queue)#线程任务就是将网址的源代码存放到out_queue队列中
t.setDaemon(True)#设置为守护线程
#将网址都存放到queue队列中
for host in hosts:
queue.put(host)
for i in range(5):
dt = DatamineThread(out_queue)#线程任务就是从源代码中解析出
(window.slotbydup=window.slotbydup || []).push({
id: '2467140',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467141',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467142',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467143',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467148',
container: s,
size: '1000,90',
display: 'inlay-fix'一个简单的多线程Python爬虫
最近想要抓取的数据,最开始是使用Scrapy的,但是遇到了下面两个问题:
前端页面是用JS模板引擎生成的
接口主要是用POST提交参数的
目前不会处理使用JS模板引擎生成的HTML页面,用POST的提交参数的话,接口统一,也没有必要使用Scrapy,所以就萌生了自己写一个简单的Python爬虫的想法。
本文中的部分链接可能需要FQ。
参考资料:
一个爬虫的简单框架
一个简单的爬虫框架,主要就是处理网络请求,Scrapy使用的是(一个事件驱动网络框架,以非阻塞的方式对网络I/O进行异步处理),这里不使用异步处理,等以后再研究这个框架。如果使用的是Python3.4及其以上版本,到可以使用这个标准库。
这个简单的爬虫使用多线程来处理网络请求,使用线程来处理URL队列中的url,然后将url返回的结果保存在另一个队列中,其它线程在读取这个队列中的数据,然后写到文件中去。
该爬虫主要用下面几个部分组成。
1 URL队列和结果队列
将将要爬去的url放在一个队列中,这里使用标准库。访问url后的结果保存在结果队列中
初始化一个URL队列
from Queue import Queue
urls_queue = Queue()
out_queue = Queue()
2 请求线程
使用多个线程,不停的取URL队列中的url,并进行处理:
import threading
class ThreadCrawl(threading.Thread):
def __init__(self, queue, out_queue):
threading.Thread.__init__(self)
self.queue = queue
self.out_queue = out_queue
def run(self):
while True:
item = self.queue.get()
self.queue.task_down()
下面是部分标准库Queue的使用方法:
Queue.get([block[, timeout]])
Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available.
Queue.task_done()
Indicate that a formerly enqueued task is complete. Used by queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete.
如果队列为空,线程就会被阻塞,直到队列不为空。处理队列中的一条数据后,就需要通知队列已经处理完该条数据。
处理结果队列中的数据,并保存到文件中。如果使用多个线程的话,必须要给文件加上锁。
lock = threading.Lock()
f = codecs.open('out.txt', 'w', 'utf8')
当线程需要写入文件的时候,可以这样处理:
with lock:
f.write(something)
程序的执行结果
运行状态:
抓取结果:
代码还不完善,将会持续修改中。
# coding: utf-8
'''
Author mr_zys
'''
from Queue import Queue
import threading
import urllib2
import time
import json
import codecs
from bs4 import BeautifulSoup
urls_queue = Queue()
data_queue = Queue()
lock = threading.Lock()
f = codecs.open('out.txt', 'w', 'utf8')
class ThreadUrl(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
class ThreadCrawl(threading.Thread):
def __init__(self, url, queue, out_queue):
threading.Thread.__init__(self)
self.url = url
self.queue = queue
self.out_queue = out_queue
def run(self):
while True:
item = self.queue.get()
data = self._data_post(item)
req = urllib2.Request(url=self.url, data=data)
res = urllib2.urlopen(req)
except urllib2.HTTPError, e:
raise e.reason
py_data = json.loads(res.read())
res.close()
item['first'] = 'false'
item['pn'] = item['pn'] + 1
success = py_data['success']
if success:
print 'Get success...'
print 'Get fail....'
print 'pn is : %s' % item['pn']
result = py_data['content']['result']
if len(result) != 0:
self.queue.put(item)
print 'now queue size is: %d' % self.queue.qsize()
self.out_queue.put(py_data['content']['result'])
self.queue.task_done()
def _data_post(self, item):
pn = item['pn']
first = 'false'
if pn == 1:
first = 'true'
return 'first=' + first + '&pn=' + str(pn) + '&kd=' + item['kd']
def _item_queue(self):
class ThreadWrite(threading.Thread):
def __init__(self, queue, lock, f):
threading.Thread.__init__(self)
self.queue = queue
self.lock = lock
self.f = f
def run(self):
while True:
item = self.queue.get()
self._parse_data(item)
self.queue.task_done()
def _parse_data(self, item):
for i in item:
l = self._item_to_str(i)
with self.lock:
print 'write %s' % l
self.f.write(l)
def _item_to_str(self, item):
positionName = item['positionName']
positionType = item['positionType']
workYear = item['workYear']
education = item['education']
jobNature = item['jobNature']
companyName = item['companyName']
companyLogo = item['companyLogo']
industryField = item['industryField']
financeStage = item['financeStage']
companyShortName = item['companyShortName']
city = item['city']
salary = item['salary']
positionFirstType = item['positionFirstType']
createTime = item['createTime']
positionId = item['positionId']
return positionName + ' ' + positionType + ' ' + workYear + ' ' + education + ' ' + \
jobNature + ' ' + companyLogo + ' ' + industryField + ' ' + financeStage + ' ' + \
companyShortName + ' ' + city + ' ' + salary + ' ' + positionFirstType + ' ' + \
createTime + ' ' + str(positionId) + '\n'
def main():
for i in range(4):
t = ThreadCrawl(
'/jobs/positionAjax.json', urls_queue, data_queue)
t.setDaemon(True)
{'first': 'true', 'pn': 1, 'kd': 'Java'}
#{'first': 'true', 'pn': 1, 'kd': 'Python'}
for d in datas:
urls_queue.put(d)
for i in range(4):
t = ThreadWrite(data_queue, lock, f)
t.setDaemon(True)
urls_queue.join()
data_queue.join()
with lock:
print 'data_queue siez: %d' % data_queue.qsize()
主要是熟悉使用Python的多线程编程,以及一些标准库的使用Queue、threading。
阅读(...) 评论()}

我要回帖

更多关于 爬虫工程师面试题 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信