python定向爬虫校园论坛帖子信息


Posted in Python onJuly 23, 2018

引言

写这个小爬虫主要是为了爬校园论坛上的实习信息,主要采用了Requests库

源码

URLs.py

主要功能是根据一个初始url(包含page页面参数)来获得page页面从当前页面数到pageNum的url列表

import re

def getURLs(url, attr, pageNum=1):
  all_links = []
  try:
    now_page_number = int(re.search(attr+'=(\d+)', url, re.S).group(1))
    for i in range(now_page_number, pageNum + 1):
      new_url = re.sub(attr+'=\d+', attr+'=%s' % i, url, re.S)
      all_links.append(new_url)
    return all_links
  except TypeError:
    print "arguments TypeError:attr should be string."

uni_2_native.py

由于论坛上爬取得到的网页上的中文都是unicode编码的形式,文本格式都为 &#XXXX;的形式,所以在爬得网站内容后还需要对其进行转换

import sys
import re
reload(sys)
sys.setdefaultencoding('utf-8')

def get_native(raw):
  tostring = raw
  while True:
    obj = re.search('&#(.*?);', tostring, flags=re.S)
    if obj is None:
      break
    else:
      raw, code = obj.group(0), obj.group(1)
      tostring = re.sub(raw, unichr(int(code)), tostring)
  return tostring

存入SQLite数据库:saveInfo.py

# -*- coding: utf-8 -*-

import MySQLdb


class saveSqlite():
  def __init__(self):
    self.infoList = []

  def saveSingle(self, author=None, title=None, date=None, url=None,reply=0, view=0):
    if author is None or title is None or date is None or url is None:
      print "No info saved!"
    else:
      singleDict = {}
      singleDict['author'] = author
      singleDict['title'] = title
      singleDict['date'] = date
      singleDict['url'] = url
      singleDict['reply'] = reply
      singleDict['view'] = view
      self.infoList.append(singleDict)

  def toMySQL(self):
    conn = MySQLdb.connect(host='localhost', user='root', passwd='', port=3306, db='db_name', charset='utf8')
    cursor = conn.cursor()
    # sql = "select * from info"
    # n = cursor.execute(sql)
    # for row in cursor.fetchall():
    #   for r in row:
    #     print r
    #   print '\n'
    sql = "delete from info"
    cursor.execute(sql)
    conn.commit()

    sql = "insert into info(title,author,url,date,reply,view) values (%s,%s,%s,%s,%s,%s)"
    params = []
    for each in self.infoList:
      params.append((each['title'], each['author'], each['url'], each['date'], each['reply'], each['view']))
    cursor.executemany(sql, params)

    conn.commit()
    cursor.close()
    conn.close()


  def show(self):
    for each in self.infoList:
      print "author: "+each['author']
      print "title: "+each['title']
      print "date: "+each['date']
      print "url: "+each['url']
      print "reply: "+str(each['reply'])
      print "view: "+str(each['view'])
      print '\n'

if __name__ == '__main__':
  save = saveSqlite()
  save.saveSingle('网','aaa','2008-10-10 10:10:10','www.baidu.com',1,1)
  # save.show()
  save.toMySQL()

主要爬虫代码

import requests
from lxml import etree
from cc98 import uni_2_native, URLs, saveInfo

# 根据自己所需要爬的网站,伪造一个header
headers ={
  'Accept': '',
  'Accept-Encoding': '',
  'Accept-Language': '',
  'Connection': '',
  'Cookie': '',
  'Host': '',
  'Referer': '',
  'Upgrade-Insecure-Requests': '',
  'User-Agent': ''
}
url = 'http://www.cc98.org/list.asp?boardid=459&page=1&action='
cc98 = 'http://www.cc98.org/'

print "get infomation from cc98..."

urls = URLs.getURLs(url, "page", 50)
savetools = saveInfo.saveSqlite()

for url in urls:
  r = requests.get(url, headers=headers)
  html = uni_2_native.get_native(r.text)

  selector = etree.HTML(html)
  content_tr_list = selector.xpath('//form/table[@class="tableborder1 list-topic-table"]/tbody/tr')

  for each in content_tr_list:
    href = each.xpath('./td[2]/a/@href')
    if len(href) == 0:
      continue
    else:
      # print len(href)
      # not very well using for, though just one element in list
      # but I don't know why I cannot get the data by index
      for each_href in href:
        link = cc98 + each_href
      title_author_time = each.xpath('./td[2]/a/@title')

      # print len(title_author_time)
      for info in title_author_time:
        info_split = info.split('\n')
        title = info_split[0][1:len(info_split[0])-1]
        author = info_split[1][3:]
        date = info_split[2][3:]

      hot = each.xpath('./td[4]/text()')
      # print len(hot)
      for hot_num in hot:
        reply_view = hot_num.strip().split('/')
        reply, view = reply_view[0], reply_view[1]
      savetools.saveSingle(author=author, title=title, date=date, url=link, reply=reply, view=view)

print "All got! Now saving to Database..."
# savetools.show()
savetools.toMySQL()
print "ALL CLEAR! Have Fun!"

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python网络爬虫实例讲解
Apr 28 Python
Python+Pika+RabbitMQ环境部署及实现工作队列的实例教程
Jun 29 Python
不要用强制方法杀掉python线程
Feb 26 Python
用Python将一个列表分割成小列表的实例讲解
Jul 02 Python
python 以16进制打印输出的方法
Jul 09 Python
Python3 log10()函数简单用法
Feb 19 Python
pytorch使用Variable实现线性回归
May 21 Python
Django项目后台不挂断运行的方法
Aug 31 Python
python中从for循环延申到推导式的具体使用
Nov 29 Python
tensorflow 分类损失函数使用小记
Feb 18 Python
Python基于pyecharts实现关联图绘制
Mar 27 Python
使用python实现名片管理系统
Jun 18 Python
python实现图片批量压缩程序
Jul 23 #Python
python中的插值 scipy-interp的实现代码
Jul 23 #Python
Flask框架URL管理操作示例【基于@app.route】
Jul 23 #Python
python中的turtle库函数简单使用教程
Jul 23 #Python
Flask框架配置与调试操作示例
Jul 23 #Python
python实现时间o(1)的最小栈的实例代码
Jul 23 #Python
Flask框架Flask-Principal基本用法实例分析
Jul 23 #Python
You might like
玩转虚拟域名◎+ .
2006/10/09 PHP
PHP学习之PHP运算符
2006/10/09 PHP
php+mysqli使用预处理技术进行数据库查询的方法
2015/01/28 PHP
jquery checkbox,radio是否选中的判断代码
2010/03/20 Javascript
基于jquery的拖动布局插件
2011/11/25 Javascript
jQuery提交多个表单的小例子
2013/06/30 Javascript
jQuery读取XML文件内容的方法
2015/03/09 Javascript
jquery实现可关闭的倒计时广告特效代码
2015/09/02 Javascript
jQuery中attr()与prop()函数用法实例详解(附用法区别)
2015/12/29 Javascript
JS组件Bootstrap dropdown组件扩展hover事件
2016/04/17 Javascript
全面理解JavaScript中的闭包
2016/05/12 Javascript
微信小程序 配置文件详细介绍
2016/12/14 Javascript
JS身份证信息验证正则表达式
2017/06/12 Javascript
微信小程序 sha1 实现密码加密实例详解
2017/07/06 Javascript
JavaScript实现三级联动菜单效果
2017/08/16 Javascript
Windows下使用Nodejs运行js的方法
2017/09/02 NodeJs
微信小程序实现animation动画
2018/01/26 Javascript
利用nodeJs anywhere搭建本地服务器环境的方法
2018/05/12 NodeJs
jQuery 点击获取验证码按钮及倒计时功能
2018/09/20 jQuery
详解VUE单页应用骨架屏方案
2019/01/17 Javascript
基于javascript的拖拽类封装详解
2019/04/19 Javascript
[02:40]DOTA2殁境神蚀者 英雄基础教程
2013/11/26 DOTA
Python实现统计英文单词个数及字符串分割代码
2015/05/28 Python
Windows和Linux下Python输出彩色文字的方法教程
2017/05/02 Python
django2+uwsgi+nginx上线部署到服务器Ubuntu16.04
2018/06/26 Python
python简易实现任意位数的水仙花实例
2018/11/13 Python
PIL包中Image模块的convert()函数的具体使用
2020/02/26 Python
thinkphp5 路由分发原理
2021/03/18 PHP
师范生自荐信
2013/10/27 职场文书
公证委托书格式
2014/09/13 职场文书
专题民主生活会对照检查材料思想汇报
2014/09/29 职场文书
教师自查自纠工作情况报告
2014/10/29 职场文书
2014年城管个人工作总结
2014/12/08 职场文书
Oracle设置DB、监听和EM开机启动的方法
2021/04/25 Oracle
Axios代理配置及封装响应拦截处理方式
2022/04/07 Vue.js
MySQL时区造成时差问题
2022/04/13 MySQL