Python实现的文轩网爬虫完整示例

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

encoding=utf8
import pymysql
import time
import sys
import requests
import os
#捕获错误
import traceback
import types
#将html实体化
import cgi
import warnings
reload(sys)
sys.setdefaultencoding('utf-8')
from pyquery import PyQuery as pq
from lxml import etree
sys.setdefaultencoding('utf-8')
#屏蔽错误
warnings.filterwarnings("ignore")
#下载图片
def dowloadPic(imageUrl,filePath):
r = requests.get(imageUrl,timeout=60)
status=r.status_code
if status == 404:
return 404
with open(filePath, "wb") as code:
code.write(r.content)
#根据详情页地址抓取数据并插入数据库
def getData(final_url):
file_open=open('./url.txt', 'w')
file_open.write(final_url)
file_open.close()
#链接数据库
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='bookinfo', charset='utf8')
#设置浮标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#解析详情页面
try:
detail_url=final_url
c=pq(detail_url)
head=c('html').attr('xmlns')
err='http://www.w3.org/1999/xhtml'
err1='http://www.winxuan.com/cms/2016db_sh'
if head == err or head == err1:
return 'back'
except Exception, e:
return 'back'
i=0
while i<12:
  text = c('#page').find('.cont').find('li').eq(i).text()
  text=text.replace(' ','')
  if 'I S B N' in text:
    isbn=text.replace('I S B N:','')
    isbn=isbn.strip()
    sel='select count(*) from bi_book where isbn ='+isbn
    cursor.execute(sel)
    result=cursor.fetchone()
    count=result['count(*)']
    if count != 0 :
      print u'已存在'
      return 'back'
  if 'isbn:' in text :
    isbn=text.replace('isbn:','')
    isbn=isbn.strip()
    sel='select count(*) from bi_book where isbn ='+isbn
    cursor.execute(sel)
    result=cursor.fetchone()
    count=result['count(*)']
    if count != 0 :
      print u'已存在'
      return 'back'
  if '作者:' in text :
    author = text.replace('作者:','')
  if '出版社:' in text :
    press_name=text.replace('出版社:','')
  if '版次:' in text :
    edition=text.replace('版次:','')
  if '印次:' in text :
    impressions=text.replace('印次:','')
  if '装帧:' in text :
    packaging=text.replace('装帧:','')
  if '开本:' in text:
    size=text.replace('开本:','')
  if '出版时间:' in text:
    press_time=text.replace('出版时间:','')
    press_time=press_time.strip()
    if press_time == '无':
      press_time='1970-01-01'
  if '印刷时间:' in text:
    print_time=text.replace('印刷时间:','')
    print_time=print_time.strip()
    if print_time== '无':
      print_time='1970-01-01'
  if '页数:' in text:
    page_num=text.replace('页数:','')
  if '字数:' in text:
    word_num=text.replace('字数:','')
  i+=1
if ('author' in locals().keys()) == False:
  author = ''
if ('press_time' in locals().keys()) == False:
  press_time = '1970-01-01'
if ('print_time' in locals().keys()) == False:
  print_time = '1970-01-01'
if ('impressions' in locals().keys()) == False:
  impressions = ''
if ('edition' in locals().keys())== False:
  edition = ''
if ('page_num' in locals().keys())== False:
  page_num = ''
if ('word_num' in locals().keys())== False:
  word_num = ''
if ('packaging' in locals().keys())== False:
  packaging = ''
if ('size' in locals().keys())== False:
  size = ''
if ('press_name' in locals().keys())== False:
  press_name = ''
#暂无图片地址
none_img='http://static.winxuancdn.com/goods/sml_blank.jpg'
#获取大小图地址
big_path=c('.info-side').find('.img').find('a').find('img').attr('src')
if big_path is None:
  return 'back'
elif big_path == none_img :
  big_path=''
  small_path=''
else :
  small_path=big_path.replace('_16','_11')
#获取分类
#先获取a标签html
ahtml=c('#page').find('.base-nav').eq(0).html()
#解析a标签html
cate=pq(ahtml)
#获取分类的最后一个分类
category=cate('a:last').text()
#获取书名
name=c('.info-main').find('.name').eq(0).find('h1').eq(0).text()
name=name.strip()
#获取价格
price=c('.info-main').find('.attr').eq(0).find('.price-n').eq(0).find('b').text()
price=price.replace('¥','')
#循环获取内容简介和目录信息
k=5
while k<12:
  title=c('#page').find('.title').eq(k).find('.tab').find('h4').text()
  if '内容简介' in title:
    con=c('#page').find('.title').eq(k).nextAll()
    det=pq(con)
    content=det('.text-words-1').html()
    content=content.encode("utf8", "ignore");
  if '目录' in title:
    con=c('#page').find('.title').eq(k).nextAll()
    dry=pq(con)
    directory=dry('.text-words-1').html()
    directory=directory.encode("utf8", "ignore");
  k+=1
#如果内容简介和目录没有的时候指定为空字符串
if ('content' in locals().keys())== False:
  content = ''
if ('directory' in locals().keys())== False:
  directory = ''
details  = '内容简介<br>'+content+'<br><br>目录<br>'+directory
details=cgi.escape(details)
#录入时间
add_time = time.strftime('%Y-%m-%d',time.localtime(time.time()))
#下载小图
#文件根目录
root_path=sys.path[0]
#创建isbn文件夹路径
root_path=root_path.replace('\\','/')
isbn_path=root_path+'/download/'+isbn
if big_path != '' and small_path !='' :
  #创建isbn目录
  if os.path.isdir(isbn_path) ==False :
    os.mkdir(isbn_path)
    #组合下载后图片保存路径
    down_img_small = isbn_path+"/small"+isbn+".jpg"
    down_img_big  = isbn_path+'/big'+isbn+".jpg"
    #调用下载图片方法
    small_res=dowloadPic(small_path,down_img_small)
    #大图保存数据库路径
    big_res=dowloadPic(big_path,down_img_big)
    #小图保存数据库路径
    if small_res==404 :
      img_small = 'none-picture/none-small.jpg'
    else :
      img_small = 'download/'+isbn+'/small'+isbn+'.jpg'
    if big_res==404 :
      img_big = 'none-picture/none-big.jpg'
    else :
      img_big  = 'download/'+isbn+'/big'+isbn+'.jpg'
  else :
    #组合保存数据库中的图片路径
    img_small = 'download/'+isbn+'/small'+isbn+'.jpg'
    img_big  = 'download/'+isbn+'/big'+isbn+'.jpg'
else :
  img_big = 'none-picture/none-big.jpg'
  img_small = 'none-picture/none-small.jpg'
source_type = 3
try :
  #要插入的列表
  li=[0,source_type,category,details,detail_url,price,add_time,packaging,print_time,impressions,name,author,press_name,isbn,edition,size,press_time,page_num,word_num,img_big,img_small]
  #执行sql
  sql="insert into bi_book (book_id,source_type,category,details,detail_url,price,add_time,packaging,print_time,impressions,name,author,press_name,isbn,edition,size,press_time,page_num,word_num,img_big,img_small) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
  aaa=cursor.execute(sql,li)
  if aaa==1:
    print u'插入成功'
  conn.commit()
except Exception, e :
  return 'back'
def winxuan(n):
#首页解析
home_url='http://www.winxuan.com/'
h=pq(home_url)
#分类导航链接
menu=h('.mod-mainmenu').find('dd').find('a').eq(n).attr('href')
#print menu
#分类书籍首页
try:
mh=pq(menu)
except Exception, e :
return 'backs'
# text=mh('.main').find('a').text()
# text=text.encode("GBK", "ignore");
li=[]
u=0
while u<248 :
detail_urls=mh('.main').find('a').eq(u).attr('href')
#将取到所有地址放入到列表当中
li.append(detail_urls)
u+=1
#进行列表去重
li=list(set(li))
for final_url in li:
try:
result=getData(final_url)
except Exception, e :
continue
if result=='back' :
continue
print 'OK,finished'
n=0
while n<58:
while n<58:
print n
string=str(n)
file_open=open('./number.txt', 'w')
file_open.write(string)
file_open.close()
res=winxuan(n)
n+=1
if res=='backs' :
continue

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

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

(0)

相关推荐

  • python爬虫实战之爬取京东商城实例教程

    前言 本文主要介绍的是利用python爬取京东商城的方法,文中介绍的非常详细,下面话不多说了,来看看详细的介绍吧. 主要工具 scrapy BeautifulSoup requests 分析步骤 1.打开京东首页,输入裤子将会看到页面跳转到了这里,这就是我们要分析的起点 2.我们可以看到这个页面并不是完全的,当我们往下拉的时候将会看到图片在不停的加载,这就是ajax,但是当我们下拉到底的时候就会看到整个页面加载了60条裤子的信息,我们打开chrome的调试工具,查找页面元素时可以看到每条裤子的信

  • 零基础写python爬虫之使用Scrapy框架编写爬虫

    网络爬虫,是在网上进行数据抓取的程序,使用它能够抓取特定网页的HTML数据.虽然我们利用一些库开发一个爬虫程序,但是使用框架可以大大提高效率,缩短开发时间.Scrapy是一个使用Python编写的,轻量级的,简单轻巧,并且使用起来非常的方便.使用Scrapy可以很方便的完成网上数据的采集工作,它为我们完成了大量的工作,而不需要自己费大力气去开发. 首先先要回答一个问题. 问:把网站装进爬虫里,总共分几步? 答案很简单,四步: 新建项目 (Project):新建一个新的爬虫项目 明确目标(Item

  • Python天气预报采集器实现代码(网页爬虫)

    爬虫简单说来包括两个步骤:获得网页文本.过滤得到数据. 1.获得html文本. python在获取html方面十分方便,寥寥数行代码就可以实现我们需要的功能. 复制代码 代码如下: def getHtml(url): page = urllib.urlopen(url) html = page.read() page.close() return html 这么几行代码相信不用注释都能大概知道它的意思. 2.根据正则表达式等获得需要的内容. 使用正则表达式时需要仔细观察该网页信息的结构,并写出正

  • 零基础写python爬虫之HTTP异常处理

    先来说一说HTTP的异常处理问题. 当urlopen不能够处理一个response时,产生urlError. 不过通常的Python APIs异常如ValueError,TypeError等也会同时产生. HTTPError是urlError的子类,通常在特定HTTP URLs中产生. 1.URLError 通常,URLError在没有网络连接(没有路由到特定服务器),或者服务器不存在的情况下产生. 这种情况下,异常同样会带有"reason"属性,它是一个tuple(可以理解为不可变的

  • python3简单实现微信爬虫

    使用ghost.py 通过搜搜 的微信搜索来爬取微信公共账号的信息 # -*- coding: utf-8 -*- import sys reload(sys) import datetime import time sys.setdefaultencoding("utf-8") from ghost import Ghost ghost = Ghost(wait_timeout=20) url="http://weixin.sogou.com/gzh?openid=oIWs

  • 使用Python编写简单网络爬虫抓取视频下载资源

    我第一次接触爬虫这东西是在今年的5月份,当时写了一个博客搜索引擎,所用到的爬虫也挺智能的,起码比电影来了这个站用到的爬虫水平高多了! 回到用Python写爬虫的话题. Python一直是我主要使用的脚本语言,没有之一.Python的语言简洁灵活,标准库功能强大,平常可以用作计算器,文本编码转换,图片处理,批量下载,批量处理文本等.总之我很喜欢,也越用越上手,这么好用的一个工具,一般人我不告诉他... 因为其强大的字符串处理能力,以及urllib2,cookielib,re,threading这些

  • python编写爬虫小程序

    起因 深夜忽然想下载一点电子书来扩充一下kindle,就想起来python学得太浅,什么"装饰器"啊."多线程"啊都没有学到. 想到廖雪峰大神的python教程很经典.很著名.就想找找有木有pdf版的下载,结果居然没找到!!CSDN有个不完整的还骗走了我一个积分!!尼玛!! 怒了,准备写个程序直接去爬廖雪峰的教程,然后再html转成电子书. 过程 过程很有趣呢,用浅薄的python知识,写python程序,去爬python教程,来学习python.想想有点小激动--

  • python模拟新浪微博登陆功能(新浪微博爬虫)

    1.主函数(WeiboMain.py): 复制代码 代码如下: import urllib2import cookielib import WeiboEncodeimport WeiboSearch if __name__ == '__main__':    weiboLogin = WeiboLogin('×××@gmail.com', '××××')#邮箱(账号).密码    if weiboLogin.Login() == True:        print "登陆成功!" 前

  • 零基础写python爬虫之神器正则表达式

    接下来准备用糗百做一个爬虫的小例子. 但是在这之前,先详细的整理一下Python中的正则表达式的相关内容. 正则表达式在Python爬虫中的作用就像是老师点名时用的花名册一样,是必不可少的神兵利器. 一. 正则表达式基础 1.1.概念介绍 正则表达式是用于处理字符串的强大工具,它并不是Python的一部分. 其他编程语言中也有正则表达式的概念,区别只在于不同的编程语言实现支持的语法数量不同. 它拥有自己独特的语法以及一个独立的处理引擎,在提供了正则表达式的语言里,正则表达式的语法都是一样的. 下

  • Python实现爬取知乎神回复简单爬虫代码分享

    看知乎的时候发现了一个 "如何正确地吐槽" 收藏夹,里面的一些神回复实在很搞笑,但是一页一页地看又有点麻烦,而且每次都要打开网页,于是想如果全部爬下来到一个文件里面,是不是看起来很爽,并且随时可以看到全部的,于是就开始动手了. 工具 1.Python 2.7 2.BeautifulSoup 分析网页 我们先来看看知乎上该网页的情况 网址:,容易看到,网址是有规律的,page慢慢递增,这样就能够实现全部爬取了. 再来看一下我们要爬取的内容: 我们要爬取两个内容:问题和回答,回答仅限于显示

  • 零基础写python爬虫之urllib2使用指南

    前面说到了urllib2的简单入门,下面整理了一部分urllib2的使用细节. 1.Proxy 的设置 urllib2 默认会使用环境变量 http_proxy 来设置 HTTP Proxy. 如果想在程序中明确控制 Proxy 而不受环境变量的影响,可以使用代理. 新建test14来实现一个简单的代理Demo: 复制代码 代码如下: import urllib2  enable_proxy = True  proxy_handler = urllib2.ProxyHandler({"http&

随机推荐