Python实现的爬虫功能代码


Posted in Python onJune 24, 2017

本文实例讲述了Python实现的爬虫功能。分享给大家供大家参考,具体如下:

主要用到urllib2、BeautifulSoup模块

#encoding=utf-8
import re
import requests
import urllib2
import datetime
import MySQLdb
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
class Splider(object):
  def __init__(self):
  print u'开始爬取内容...'
  ##用来获取网页源代码
  def getsource(self,url):
  headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2652.0 Safari/537.36'}
  req = urllib2.Request(url=url,headers=headers)
  socket = urllib2.urlopen(req)
  content = socket.read()
  socket.close()
  return content
  ##changepage用来生产不同页数的链接
  def changepage(self,url,total_page):
    now_page = int(re.search('page/(\d+)',url,re.S).group(1))
  page_group = []
  for i in range(now_page,total_page+1):
    link = re.sub('page/(\d+)','page/%d' % i,url,re.S)
    page_group.append(link)
  return page_group
  #获取字内容
  def getchildrencon(self,child_url):
  conobj = {}
  content = self.getsource(child_url)
  soup = BeautifulSoup(content, 'html.parser', from_encoding='utf-8')
  content = soup.find('div',{'class':'c-article_content'})
  img = re.findall('src="(.*?)"',str(content),re.S)
  conobj['con'] = content.get_text()
  conobj['img'] = (';').join(img)
  return conobj
  ##获取内容
  def getcontent(self,html_doc):
  soup = BeautifulSoup(html_doc, 'html.parser', from_encoding='utf-8')
  tag = soup.find_all('div',{'class':'promo-feed-headline'})
  info = {}
  i = 0
  for link in tag:
    info[i] = {}
    title_desc = link.find('h3')
    info[i]['title'] = title_desc.get_text()
    post_date = link.find('div',{'class':'post-date'})
    pos_d = post_date['data-date'][0:10]
    info[i]['content_time'] = pos_d
    info[i]['source'] = 'whowhatwear'
    source_link = link.find('a',href=re.compile(r"section=fashion-trends"))
    source_url = 'http://www.whowhatwear.com'+source_link['href']
    info[i]['source_url'] = source_url
    in_content = self.getsource(source_url)
    in_soup = BeautifulSoup(in_content, 'html.parser', from_encoding='utf-8')
    soup_content = in_soup.find('section',{'class':'widgets-list-content'})
    info[i]['content'] = soup_content.get_text().strip('\n')
    text_con = in_soup.find('section',{'class':'text'})
    summary = text_con.get_text().strip('\n') if text_con.text != None else NULL
    info[i]['summary'] = summary[0:200]+'...';
    img_list = re.findall('src="(.*?)"',str(soup_content),re.S)
    info[i]['imgs'] = (';').join(img_list)
    info[i]['create_time'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    i+=1
  #print info
  #exit()
  return info
  def saveinfo(self,content_info):
  conn = MySQLdb.Connect(host='127.0.0.1',user='root',passwd='123456',port=3306,db='test',charset='utf8')
  cursor = conn.cursor()
  for each in content_info:
    for k,v in each.items():
    sql = "insert into t_fashion_spider2(`title`,`summary`,`content`,`content_time`,`imgs`,`source`,`source_url`,`create_time`) values ('%s','%s','%s','%s','%s','%s','%s','%s')" % (MySQLdb.escape_string(v['title']),MySQLdb.escape_string(v['summary']),MySQLdb.escape_string(v['content']),v['content_time'],v['imgs'],v['source'],v['source_url'],v['create_time'])
    cursor.execute(sql)
  conn.commit()
  cursor.close()
  conn.close()
if __name__ == '__main__':
  classinfo = []
  p_num = 5
  url = 'http://www.whowhatwear.com/section/fashion-trends/page/1'
  jikesplider = Splider()
  all_links = jikesplider.changepage(url,p_num)
  for link in all_links:
  print u'正在处理页面:' + link
  html = jikesplider.getsource(link)
  info = jikesplider.getcontent(html)
  classinfo.append(info)
  jikesplider.saveinfo(classinfo)

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python实现获取某天是某个月中的第几周
Feb 11 Python
Django中实现点击图片链接强制直接下载的方法
May 14 Python
PyQt5利用QPainter绘制各种图形的实例
Oct 19 Python
Python自然语言处理之词干,词形与最大匹配算法代码详解
Nov 16 Python
python队列queue模块详解
Apr 27 Python
对Python的zip函数妙用,旋转矩阵详解
Dec 13 Python
详解python 爬取12306验证码
May 10 Python
Python实现微信小程序支付功能
Jul 25 Python
Python代码块及缓存机制原理详解
Dec 13 Python
Pycharm操作Git及GitHub的步骤详解
Oct 27 Python
Python xlwings插入Excel图片的实现方法
Feb 26 Python
详细介绍python操作RabbitMq
Apr 12 Python
python3操作mysql数据库的方法
Jun 23 #Python
Python 中pandas.read_excel详细介绍
Jun 23 #Python
python3.4用函数操作mysql5.7数据库
Jun 23 #Python
Python实现树的先序、中序、后序排序算法示例
Jun 23 #Python
详解python中 os._exit() 和 sys.exit(), exit(0)和exit(1) 的用法和区别
Jun 23 #Python
Python数据操作方法封装类实例
Jun 23 #Python
Python守护线程用法实例
Jun 23 #Python
You might like
php获取数组元素中头一个数组元素值的实现方法
2014/12/20 PHP
php的4种常用运行方式详解
2016/12/22 PHP
PHP简单留言本功能实现代码
2017/06/09 PHP
tp5(thinkPHP5)操作mongoDB数据库的方法
2018/01/20 PHP
如何实现动态删除javascript函数
2007/05/27 Javascript
javascript中获取下个月一号,是星期几
2012/06/01 Javascript
Egret引擎开发指南之运行项目
2014/09/03 Javascript
jquery结合CSS使用validate实现漂亮的验证
2015/01/29 Javascript
jQuery autoComplete插件两种使用方式及动态改变参数值的方法详解
2016/10/24 Javascript
Bootstrap源码解读网格系统(3)
2016/12/22 Javascript
浅谈Vue的基本应用
2016/12/27 Javascript
vue2.0 和 animate.css的结合使用
2017/12/12 Javascript
JavaScript中变量提升与函数提升经典实例分析
2018/07/26 Javascript
解决vue2 在mounted函数无法获取prop中的变量问题
2018/11/15 Javascript
vue中的v-if和v-show的区别详解
2019/09/01 Javascript
vant实现购物车功能
2020/06/29 Javascript
Python django实现简单的邮件系统发送邮件功能
2017/07/14 Python
python模块smtplib学习
2018/05/22 Python
Python用于学习重要算法的模块pygorithm实例浅析
2018/08/16 Python
Python Selenium 之关闭窗口close与quit的方法
2019/02/13 Python
python3+PyQt5 数据库编程--增删改实例
2019/06/17 Python
django使用django-apscheduler 实现定时任务的例子
2019/07/20 Python
Django之使用内置函数和celery发邮件的方法示例
2019/09/16 Python
关于Django Models CharField 参数说明
2020/03/31 Python
Python3读取和写入excel表格数据的示例代码
2020/06/09 Python
Python局部变量与全局变量区别原理解析
2020/07/14 Python
HTML5中input[type='date']自定义样式与日历校验功能的实现代码
2017/07/11 HTML / CSS
static关键字的用法
2013/10/07 面试题
现代化办公人员工作的自我评价
2013/10/16 职场文书
煤矿开采专业求职信
2014/07/08 职场文书
志愿者爱心公益活动策划方案
2014/09/15 职场文书
关于运动会的广播稿50字
2014/10/17 职场文书
2015年校务公开工作总结
2015/05/26 职场文书
2019求职信:应届生求职信范文
2019/04/24 职场文书
使用PDF.js渲染canvas实现预览pdf的效果示例
2021/04/17 Javascript
Redis 中使用 list,streams,pub/sub 几种方式实现消息队列的问题
2022/03/16 Redis