python爬虫实例详解
作者:孙华强 发布时间:2021-07-05 01:37:53
标签:python,爬虫
本篇博文主要讲解Python爬虫实例,重点包括爬虫技术架构,组成爬虫的关键模块:URL管理器、HTML下载器和HTML解析器。
爬虫简单架构
程序入口函数(爬虫调度段)
#coding:utf8
import time, datetime
from maya_Spider import url_manager, html_downloader, html_parser, html_outputer
class Spider_Main(object):
#初始化操作
def __init__(self):
#设置url管理器
self.urls = url_manager.UrlManager()
#设置HTML下载器
self.downloader = html_downloader.HtmlDownloader()
#设置HTML解析器
self.parser = html_parser.HtmlParser()
#设置HTML输出器
self.outputer = html_outputer.HtmlOutputer()
#爬虫调度程序
def craw(self, root_url):
count = 1
self.urls.add_new_url(root_url)
while self.urls.has_new_url():
try:
new_url = self.urls.get_new_url()
print('craw %d : %s' % (count, new_url))
html_content = self.downloader.download(new_url)
new_urls, new_data = self.parser.parse(new_url, html_content)
self.urls.add_new_urls(new_urls)
self.outputer.collect_data(new_data)
if count == 10:
break
count = count + 1
except:
print('craw failed')
self.outputer.output_html()
if __name__ == '__main__':
#设置爬虫入口
root_url = 'http://baike.baidu.com/view/21087.htm'
#开始时间
print('开始计时..............')
start_time = datetime.datetime.now()
obj_spider = Spider_Main()
obj_spider.craw(root_url)
#结束时间
end_time = datetime.datetime.now()
print('总用时:%ds'% (end_time - start_time).seconds)
URL管理器
class UrlManager(object):
def __init__(self):
self.new_urls = set()
self.old_urls = set()
def add_new_url(self, url):
if url is None:
return
if url not in self.new_urls and url not in self.old_urls:
self.new_urls.add(url)
def add_new_urls(self, urls):
if urls is None or len(urls) == 0:
return
for url in urls:
self.add_new_url(url)
def has_new_url(self):
return len(self.new_urls) != 0
def get_new_url(self):
new_url = self.new_urls.pop()
self.old_urls.add(new_url)
return new_url
网页下载器
import urllib
import urllib.request
class HtmlDownloader(object):
def download(self, url):
if url is None:
return None
#伪装成浏览器访问,直接访问的话csdn会拒绝
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent':user_agent}
#构造请求
req = urllib.request.Request(url,headers=headers)
#访问页面
response = urllib.request.urlopen(req)
#python3中urllib.read返回的是bytes对象,不是string,得把它转换成string对象,用bytes.decode方法
return response.read().decode()
网页解析器
import re
import urllib
from urllib.parse import urlparse
from bs4 import BeautifulSoup
class HtmlParser(object):
def _get_new_urls(self, page_url, soup):
new_urls = set()
#/view/123.htm
links = soup.find_all('a', href=re.compile(r'/item/.*?'))
for link in links:
new_url = link['href']
new_full_url = urllib.parse.urljoin(page_url, new_url)
new_urls.add(new_full_url)
return new_urls
#获取标题、摘要
def _get_new_data(self, page_url, soup):
#新建字典
res_data = {}
#url
res_data['url'] = page_url
#<dd class="lemmaWgt-lemmaTitle-title"><h1>Python</h1>获得标题标签
title_node = soup.find('dd', class_="lemmaWgt-lemmaTitle-title").find('h1')
print(str(title_node.get_text()))
res_data['title'] = str(title_node.get_text())
#<div class="lemma-summary" label-module="lemmaSummary">
summary_node = soup.find('div', class_="lemma-summary")
res_data['summary'] = summary_node.get_text()
return res_data
def parse(self, page_url, html_content):
if page_url is None or html_content is None:
return None
soup = BeautifulSoup(html_content, 'html.parser', from_encoding='utf-8')
new_urls = self._get_new_urls(page_url, soup)
new_data = self._get_new_data(page_url, soup)
return new_urls, new_data
网页输出器
class HtmlOutputer(object):
def __init__(self):
self.datas = []
def collect_data(self, data):
if data is None:
return
self.datas.append(data )
def output_html(self):
fout = open('maya.html', 'w', encoding='utf-8')
fout.write("<head><meta http-equiv='content-type' content='text/html;charset=utf-8'></head>")
fout.write('<html>')
fout.write('<body>')
fout.write('<table border="1">')
# <th width="5%">Url</th>
fout.write('''<tr style="color:red" width="90%">
<th>Theme</th>
<th width="80%">Content</th>
</tr>''')
for data in self.datas:
fout.write('<tr>\n')
# fout.write('\t<td>%s</td>' % data['url'])
fout.write('\t<td align="center"><a href=\'%s\'>%s</td>' % (data['url'], data['title']))
fout.write('\t<td>%s</td>\n' % data['summary'])
fout.write('</tr>\n')
fout.write('</table>')
fout.write('</body>')
fout.write('</html>')
fout.close()
运行结果
附:完整代码
来源:https://blog.csdn.net/sunhuaqiang1/article/details/66472363
0
投稿
猜你喜欢
- sort() 函数用于对数组单元从低到高进行排序。rsort() 函数用于对数组单元从高到低进行排序。asort() 函数用于对数组单元从低
- 相信只要学习python的同学对于虚拟环境这个概念肯定不会太陌生,虚拟环境指的是一个个单独隔离的python开发环境。各个虚拟环境之间互不干
- python的os module中有fork()函数用于生成子进程,生成的子进程是父进程的镜像,但是它们有各自的地址空间,子进程复制一份父进
- 在如今的Web设计中,图片的应用是必不可少的,为了更好地设计网站效果,大体积的图片被越来越多地应用到Web设计中来,所以,更好地优化图片文件
- 前言在CSDN发的第一篇文章,时隔两年,终于实现了爬微博的自由!本文可以解决微博预登录、识别“展开全文”并爬取完整数据、翻页设置等问题。由于
- BP算法是适用于多层神经网络的一种算法,它是建立在梯度下降法的基础上的。本文着重推导怎样利用梯度下降法来minimise Loss Func
- 第一版,能实现,但最后发现文件的顺序改变了:import osdef reename(): nm=1 pathh="/home/h
- 导语:举例:Python做一个根据后缀名整理文件的工具,先来看看效果:自动整理前:自动整理后:这样看起来就好很多了。1.准备开始之前,你要确
- 目录爬取目标站点分析编码时间爬取结果展示爬取目标站点分析本次采集的目标站点为:https://www.zaih.com/falcon/men
- 1.什么是接口接口就是一种规范与标准,在生活中经常见接口,例如:笔记本电脑的USB接口,可以将任何厂商生产的鼠标与键盘,与电脑进行链接。为什
- 选择排序:选择排序(Selection sort)是一种简单直观的 排序算法 。它的工作原理如下。首先在未排序序列中找到最小(大)元素,存放
- auto_api_test开发环境: Pycharm开发语言&版本: python3.7.8测试框架: Pytest、测试报告: A
- 如果你细心跟踪一下SQL Server数据库服务器的登录过程,你会发现口令计算其实是非常脆弱的,SQL Server数据
- 关于主机名转IP地址只记住两点即可:1、英特网协议一直都是用4字节的IP将包转发给目的地;2、至于主机名是如何转换成IP地址的,这是操作系统
- tf.reverse_sequence()简述在看bidirectional_dynamic_rnn()的源码的时候,看到了代码中有调用 r
- 背景:之前写的接口测试一直没有支持无限嵌套对比key,上次testerhome逛论坛,有人分享了他的框架,看了一下,有些地方不合适我这边自己
- 功能需求1,利用随机数模拟产生每次考试成绩2,将每次考试成绩存入到数据库3,将每次考试成绩划分优、良、中、差、不及格五类,并作为查询条件,查
- 数据库隔离级别有四种,应用《高性能mysql》一书中的说明:然后说说修改事务隔离级别的方法:1.全局修改,修改mysql.ini配置文件,在
- python3获取控制台输入的数据的方法:可以利用input()函数来获取。python3为我们提供了input()函数,该函数用来接收一个
- 一、算法 1、算法的主要思想就是将一个中缀表达式(Infix expression)转换成便