Python實(shí)現(xiàn)的文軒網(wǎng)爬蟲(chóng)完整示例
本文實(shí)例講述了Python實(shí)現(xiàn)的文軒網(wǎng)爬蟲(chóng)。分享給大家供大家參考,具體如下:
encoding=utf8
import pymysql
import time
import sys
import requests
import os
#捕獲錯(cuò)誤
import traceback
import types
#將html實(shí)體化
import cgi
import warnings
reload(sys)
sys.setdefaultencoding('utf-8')
from pyquery import PyQuery as pq
from lxml import etree
sys.setdefaultencoding('utf-8')
#屏蔽錯(cuò)誤
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)
#根據(jù)詳情頁(yè)地址抓取數(shù)據(jù)并插入數(shù)據(jù)庫(kù)
def getData(final_url):
file_open=open('./url.txt', 'w')
file_open.write(final_url)
file_open.close()
#鏈接數(shù)據(jù)庫(kù)
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='bookinfo', charset='utf8')
#設(shè)置浮標(biāo)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#解析詳情頁(yè)面
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 '開(kāi)本:' in text:
size=text.replace('開(kāi)本:','')
if '出版時(shí)間:' in text:
press_time=text.replace('出版時(shí)間:','')
press_time=press_time.strip()
if press_time == '無(wú)':
press_time='1970-01-01'
if '印刷時(shí)間:' in text:
print_time=text.replace('印刷時(shí)間:','')
print_time=print_time.strip()
if print_time== '無(wú)':
print_time='1970-01-01'
if '頁(yè)數(shù):' in text:
page_num=text.replace('頁(yè)數(shù):','')
if '字?jǐn)?shù):' in text:
word_num=text.replace('字?jǐn)?shù):','')
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 = ''
#暫無(wú)圖片地址
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標(biāo)簽html
ahtml=c('#page').find('.base-nav').eq(0).html()
#解析a標(biāo)簽html
cate=pq(ahtml)
#獲取分類的最后一個(gè)分類
category=cate('a:last').text()
#獲取書(shū)名
name=c('.info-main').find('.name').eq(0).find('h1').eq(0).text()
name=name.strip()
#獲取價(jià)格
price=c('.info-main').find('.attr').eq(0).find('.price-n').eq(0).find('b').text()
price=price.replace('¥','')
#循環(huán)獲取內(nèi)容簡(jiǎn)介和目錄信息
k=5
while k<12:
title=c('#page').find('.title').eq(k).find('.tab').find('h4').text()
if '內(nèi)容簡(jiǎn)介' 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
#如果內(nèi)容簡(jiǎn)介和目錄沒(méi)有的時(shí)候指定為空字符串
if ('content' in locals().keys())== False:
content = ''
if ('directory' in locals().keys())== False:
directory = ''
details = '內(nèi)容簡(jiǎn)介<br>'+content+'<br><br>目錄<br>'+directory
details=cgi.escape(details)
#錄入時(shí)間
add_time = time.strftime('%Y-%m-%d',time.localtime(time.time()))
#下載小圖
#文件根目錄
root_path=sys.path[0]
#創(chuàng)建isbn文件夾路徑
root_path=root_path.replace('\\','/')
isbn_path=root_path+'/download/'+isbn
if big_path != '' and small_path !='' :
#創(chuàng)建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"
#調(diào)用下載圖片方法
small_res=dowloadPic(small_path,down_img_small)
#大圖保存數(shù)據(jù)庫(kù)路徑
big_res=dowloadPic(big_path,down_img_big)
#小圖保存數(shù)據(jù)庫(kù)路徑
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 :
#組合保存數(shù)據(jù)庫(kù)中的圖片路徑
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]
#執(zhí)行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):
#首頁(yè)解析
home_url='http://www.winxuan.com/'
h=pq(home_url)
#分類導(dǎo)航鏈接
menu=h('.mod-mainmenu').find('dd').find('a').eq(n).attr('href')
#print menu
#分類書(shū)籍首頁(yè)
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')
#將取到所有地址放入到列表當(dāng)中
li.append(detail_urls)
u+=1
#進(jìn)行列表去重
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
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python正則表達(dá)式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門(mén)與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
- 使用Python編寫(xiě)簡(jiǎn)單網(wǎng)絡(luò)爬蟲(chóng)抓取視頻下載資源
- 零基礎(chǔ)寫(xiě)python爬蟲(chóng)之使用Scrapy框架編寫(xiě)爬蟲(chóng)
- python模擬新浪微博登陸功能(新浪微博爬蟲(chóng))
- 零基礎(chǔ)寫(xiě)python爬蟲(chóng)之HTTP異常處理
- 零基礎(chǔ)寫(xiě)python爬蟲(chóng)之神器正則表達(dá)式
- python編寫(xiě)爬蟲(chóng)小程序
- 零基礎(chǔ)寫(xiě)python爬蟲(chóng)之urllib2使用指南
- python3簡(jiǎn)單實(shí)現(xiàn)微信爬蟲(chóng)
- Python實(shí)現(xiàn)爬取知乎神回復(fù)簡(jiǎn)單爬蟲(chóng)代碼分享
- python爬蟲(chóng)實(shí)戰(zhàn)之爬取京東商城實(shí)例教程
- Python天氣預(yù)報(bào)采集器實(shí)現(xiàn)代碼(網(wǎng)頁(yè)爬蟲(chóng))
相關(guān)文章
Python?ChineseCalendar包主要類和方法詳解
ChineseCalendar?是一個(gè)?Python?包,用于獲取中國(guó)傳統(tǒng)日歷信息。這個(gè)包提供了中國(guó)農(nóng)歷、二十四節(jié)氣、傳統(tǒng)節(jié)日、黃歷等信息,這篇文章主要介紹了Python?ChineseCalendar包簡(jiǎn)介,需要的朋友可以參考下2023-03-03
python正則表達(dá)式常見(jiàn)的知識(shí)點(diǎn)匯總
正則表達(dá)式提供了一些可用的匹配模式,比如忽略大小寫(xiě)、多行匹配等,下面這篇文章主要給大家介紹了關(guān)于python正則表達(dá)式常見(jiàn)的知識(shí)點(diǎn),文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05
Python實(shí)現(xiàn)Excel和CSV之間的相互轉(zhuǎn)換
通過(guò)使用Python編程語(yǔ)言,編寫(xiě)腳本來(lái)自動(dòng)化Excel和CSV之間的轉(zhuǎn)換過(guò)程,可以批量處理大量文件,定期更新數(shù)據(jù),并集成轉(zhuǎn)換過(guò)程到自動(dòng)化工作流程中,本文將介紹如何使用Python 實(shí)現(xiàn)Excel和CSV之間的相互轉(zhuǎn)換,需要的朋友可以參考下2024-03-03
Pandas 解決dataframe的一列進(jìn)行向下順移問(wèn)題
今天小編就為大家分享一篇Pandas 解決dataframe的一列進(jìn)行向下順移問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12
Python數(shù)據(jù)分析之如何利用pandas查詢數(shù)據(jù)示例代碼
查詢和分析數(shù)據(jù)是pandas的重要功能,也是我們學(xué)習(xí)pandas的基礎(chǔ),下面這篇文章主要給大家介紹了關(guān)于Python數(shù)據(jù)分析之如何利用pandas查詢數(shù)據(jù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-09-09
Python標(biāo)準(zhǔn)庫(kù)之urllib和urllib3的使用及說(shuō)明
這篇文章主要介紹了Python標(biāo)準(zhǔn)庫(kù)之urllib和urllib3使用及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
Python標(biāo)準(zhǔn)庫(kù)inspect的具體使用方法
本篇文章主要介紹了Python標(biāo)準(zhǔn)庫(kù)inspect的具體使用方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-12-12
如何在python開(kāi)發(fā)工具PyCharm中搭建QtPy環(huán)境(教程詳解)
這篇文章主要介紹了在python開(kāi)發(fā)工具PyCharm中搭建QtPy環(huán)境,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02

