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

引言

写这个小爬虫主要是为了爬校园论坛上的实习信息,主要采用了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!"

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

(0)

相关推荐

  • Python爬虫框架Scrapy常用命令总结

    本文实例讲述了Python爬虫框架Scrapy常用命令.分享给大家供大家参考,具体如下: 在Scrapy中,工具命令分为两种,一种为全局命令,一种为项目命令. 全局命令不需要依靠Scrapy项目就可以在全局中直接运行,而项目命令必须要在Scrapy项目中才可以运行 全局命令 全局命令有哪些呢,要想了解在Scrapy中有哪些全局命令,可以在不进入Scrapy项目所在目录的情况下,运行scrapy-h,如图所示: 可以看到,此时在可用命令在终端下展示出了常见的全局命令,分别为fetch.runspi

  • Python简单爬虫导出CSV文件的实例讲解

    流程:模拟登录→获取Html页面→正则解析所有符合条件的行→逐一将符合条件的行的所有列存入到CSVData[]临时变量中→写入到CSV文件中 核心代码: ####写入Csv文件中 with open(self.CsvFileName, 'wb') as csvfile: spamwriter = csv.writer(csvfile, dialect='excel') #设置标题 spamwriter.writerow(["游戏账号","用户类型","游戏

  • Python 爬虫之Beautiful Soup模块使用指南

    爬取网页的流程一般如下: 选着要爬的网址(url) 使用 python 登录上这个网址(urlopen.requests 等) 读取网页信息(read() 出来) 将读取的信息放入 BeautifulSoup 使用 BeautifulSoup 选取 tag 信息等 可以看到,页面的获取其实不难,难的是数据的筛选,即如何获取到自己想要的数据.本文就带大家学习下 BeautifulSoup 的使用. BeautifulSoup 官网介绍如下: Beautiful Soup 是一个可以从 HTML 或

  • Python爬虫的两套解析方法和四种爬虫实现过程

    对于大多数朋友而言,爬虫绝对是学习 python 的最好的起手和入门方式.因为爬虫思维模式固定,编程模式也相对简单,一般在细节处理上积累一些经验都可以成功入门.本文想针对某一网页对  python 基础爬虫的两大解析库(  BeautifulSoup 和  lxml )和几种信息提取实现方法进行分析,以开  python 爬虫之初见. 基础爬虫的固定模式 笔者这里所谈的基础爬虫,指的是不需要处理像异步加载.验证码.代理等高阶爬虫技术的爬虫方法.一般而言,基础爬虫的两大请求库 urllib 和 

  • Python爬虫使用脚本登录Github并查看信息

    前言分析目标网站的登录方式 目标地址: https://github.com/login 登录方式做出分析: 第一,用form表单方式提交信息, 第二,有csrf_token, 第三 ,是以post请求发送用户名和密码时,需要第一次get请求的cookie 第四,登录成功以后,请求其他页面是只需要带第一次登录成功以后返回的cookie就可以. 以get发送的请求获取我们想要的token和cookie 代码: import requests from bs4 import BeautifulSou

  • python使用tornado实现简单爬虫

    本文实例为大家分享了python使用tornado实现简单爬虫的具体代码,供大家参考,具体内容如下 代码在官方文档的示例代码中有,但是作为一个tornado新手来说阅读起来还是有点困难的,于是我在代码中添加了注释,方便理解,代码如下: # coding=utf-8 #!/usr/bin/env python import time from datetime import timedelta try: from HTMLParser import HTMLParser from urlparse

  • python爬虫之urllib3的使用示例

    Urllib3是一个功能强大,条理清晰,用于HTTP客户端的Python库.许多Python的原生系统已经开始使用urllib3.Urllib3提供了很多python标准库urllib里所没有的重要特性: 线程安全 连接池 客户端SSL/TLS验证 文件分部编码上传 协助处理重复请求和HTTP重定位 支持压缩编码 支持HTTP和SOCKS代理 一.get请求 urllib3主要使用连接池进行网络请求的访问,所以访问之前我们需要创建一个连接池对象,如下所示: import urllib3 url

  • Python爬虫实现简单的爬取有道翻译功能示例

    本文实例讲述了Python爬虫实现简单的爬取有道翻译功能.分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #!python3 import urllib.request import urllib.parse import json while True : content = input("请输入需要翻译的内容:(按q退出)") if content == 'q' : break url = 'http://fanyi.youdao.com/trans

  • Python爬虫框架Scrapy基本用法入门教程

    本文实例讲述了Python爬虫框架Scrapy基本用法.分享给大家供大家参考,具体如下: Xpath <html> <head> <title>标题</title> </head> <body> <h2>二级标题</h2> <p>爬虫1</p> <p>爬虫2</p> </body> </html> 在上述html代码中,我要获取h2的内容,

  • Python爬虫之网页图片抓取的方法

    一.引入 这段时间一直在学习Python的东西,以前就听说Python爬虫多厉害,正好现在学到这里,跟着小甲鱼的Python视频写了一个爬虫程序,能实现简单的网页图片下载. 二.代码 __author__ = "JentZhang" import urllib.request import os import random import re def url_open(url): ''' 打开网页 :param url: :return: ''' req = urllib.reques

  • python高阶爬虫实战分析

    关于这篇文章有几句话想说,首先给大家道歉,之前学的时候真的觉得下述的是比较厉害的东西,但是后来发现真的是基础中的基础,内容还不是很完全.再看一遍自己写的这篇文章,突然有种想自杀的冲动.emmm所以楼主决定本文全文抹掉重写一遍,并且为之前点进来看的七十多访问量的人,致以最诚挚的歉意.好想死.. 在学完了爬虫全部内容后,楼主觉得勉强有资格为接触爬虫的新人指指路了.那么废话不多说,以下正文: 一.获取内容 说爬虫一定要先说爬取内容的方法,python有这么几个支持爬虫的库,一个是urllib和它的后续

随机推荐