亚洲免费在线-亚洲免费在线播放-亚洲免费在线观看-亚洲免费在线观看视频-亚洲免费在线看-亚洲免费在线视频

Python實現的文軒網爬蟲完整示例

系統 1792 0

本文實例講述了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  = '內容簡介
            
'+content+'

目錄
'+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程序設計有所幫助。


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 国产一区二区三区高清视频 | 亚洲高清在线观看播放 | 日本久久免费 | 国内一级特黄女人精品片 | 色综合久久天天影视网 | 亚洲欧美一区二区三区不卡 | 日本一级毛一级毛片短视频 | 国产中文欧美 | 2020久久国产精品福利 | 国产精品久久久久久久久久妇女 | 久久久毛片免费全部播放 | 97影院理论午夜论不卡 | 伊人久久精品成人网 | 欧美成人精品不卡视频在线观看 | 久久久久久影院 | 奇米网7777| 99re这里只有精品在线 | 国产精品人成人免费国产 | 久久国产精品免费看 | 免费欧美黄色网址 | 四虎影视库永久在线地址 | 免费一区 | 久久香蕉国产精品一区二区三 | 久久久久久综合对白国产 | 四虎影永久在线观看精品 | 99久热成人精品视频 | 毛片在线视频观看 | 日韩精品免费一区二区 | 午夜精品亚洲 | 久久草视频 | 夜夜夜爽| 精品伊人久久久 | 国产伦码精品一区二区 | 女人182毛片a级毛片 | 亚欧美| 黄色自拍网站 | 色狠狠婷婷97| 成人综合久久精品色婷婷 | 亚洲一区二区三区精品影院 | 日日摸天天摸狠狠摸摸 | 黄a毛片|