python爬虫实例详解

作者:孙华强 时间:2021-07-05 01:37:53 

本篇博文主要讲解Python爬虫实例,重点包括爬虫技术架构,组成爬虫的关键模块:URL管理器、HTML下载器和HTML解析器。

爬虫简单架构

python爬虫实例详解

程序入口函数(爬虫调度段)


#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()

运行结果

python爬虫实例详解

附:完整代码

来源:https://blog.csdn.net/sunhuaqiang1/article/details/66472363

标签:python,爬虫
0
投稿

猜你喜欢

  • 常见Dreamweaver使用过程中的问题及解决办法

    2011-03-17 16:16:00
  • 使用javascript提交form表单方法汇总

    2023-08-23 09:03:48
  • 详解CentOS 6.5中安装mysql 5.7.16 linux glibc2.5 x86 64(推荐)

    2024-01-15 19:01:11
  • 详解解Django 多对多表关系的三种创建方式

    2021-03-13 04:59:16
  • sysbench-0.4.12编译安装和CPU测试例子分享

    2024-01-24 10:06:21
  • tensorflow+k-means聚类简单实现猫狗图像分类的方法

    2022-11-04 10:45:27
  • Python多进程库multiprocessing中进程池Pool类的使用详解

    2022-11-22 03:21:11
  • 网页表单项Input的高级限制级用法

    2008-10-27 16:50:00
  • Python全栈之进程和守护进程

    2021-11-25 18:05:44
  • python基于C/S模式实现聊天室功能

    2021-05-01 04:17:53
  • golang grpc配置使用实战

    2024-02-06 01:17:09
  • python 计算方位角实例(根据两点的坐标计算)

    2023-08-01 09:30:54
  • 详解css定位与定位应用

    2007-05-11 16:52:00
  • python求素数示例分享

    2021-06-16 12:01:48
  • Python3.5运算符操作实例详解

    2021-06-09 11:41:17
  • 从客户端提升SQL Server数据库性能

    2009-03-06 14:27:00
  • mysql修改密码的三方法和忘记root密码的解决方法

    2024-01-24 18:45:12
  • Java使用jdbc连接实现对MySQL增删改查操作的全过程

    2024-01-27 05:07:51
  • python 遍历可迭代对象的实现方法

    2021-03-02 07:13:07
  • python字符串,元组,列表,字典互转代码实例详解

    2022-03-01 22:51:55
  • asp之家 网络编程 m.aspxhome.com