最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python書籍信息爬蟲實(shí)例

 更新時間:2018年03月19日 08:39:33   作者:moxiaomomo  
這篇文章主要為大家詳細(xì)介紹了python書籍信息爬蟲示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下

python書籍信息爬蟲示例,供大家參考,具體內(nèi)容如下

背景說明

需要收集一些書籍信息,以豆瓣書籍條目作為源,得到一些有效書籍信息,并保存到本地?cái)?shù)據(jù)庫。

獲取書籍分類標(biāo)簽

具體可參考這個鏈接:
https://book.douban.com/tag/?view=type

然后將這些分類標(biāo)簽鏈接存到本地某個文件,存儲內(nèi)容如下

https://book.douban.com/tag/小說
https://book.douban.com/tag/外國文學(xué)
https://book.douban.com/tag/文學(xué)
https://book.douban.com/tag/隨筆
https://book.douban.com/tag/中國文學(xué)
https://book.douban.com/tag/經(jīng)典
https://book.douban.com/tag/日本文學(xué)
https://book.douban.com/tag/散文
https://book.douban.com/tag/村上春樹
https://book.douban.com/tag/詩歌
https://book.douban.com/tag/童話
......

獲取書籍信息,并保存本地?cái)?shù)據(jù)庫

假設(shè)已經(jīng)建好mysql表,如下:

CREATE TABLE `book_info` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `bookid` varchar(64) NOT NULL COMMENT 'book ID',
 `tag` varchar(32) DEFAULT '' COMMENT '分類目錄',
 `bookname` varchar(256) NOT NULL COMMENT '書名',
 `subname` varchar(256) NOT NULL COMMENT '二級書名',
 `author` varchar(256) DEFAULT '' COMMENT '作者',
 `translator` varchar(256) DEFAULT '' COMMENT '譯者',
 `press` varchar(128) DEFAULT '' COMMENT '出版社',
 `publishAt` date DEFAULT '0000-00-00' COMMENT '出版日期',
 `stars` float DEFAULT '0' COMMENT '評分',
 `price_str` varchar(32) DEFAULT '' COMMENT '價格string',
 `hotcnt` int(11) DEFAULT '0' COMMENT '評論人數(shù)',
 `bookdesc` varchar(8192) DEFAULT NULL COMMENT '簡介',
 `updateAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改日期',
 PRIMARY KEY (`id`),
 UNIQUE KEY `idx_bookid` (`bookid`),
 KEY `idx_bookname` (`bookname`),
 KEY `hotcnt` (`hotcnt`),
 KEY `stars` (`stars`),
 KEY `idx_tag` (`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='書籍信息';

并已實(shí)現(xiàn)相關(guān)爬蟲邏輯,主要用到了BeautifulSoup包,如下:

#!/usr/bin/python
# coding: utf-8

import re
import logging
import requests
import pymysql
import random
import time
import datetime
from hashlib import md5
from bs4 import BeautifulSoup

logging.basicConfig(level=logging.INFO,
     format='[%(levelname)s][%(name)s][%(asctime)s]%(message)s',
     datefmt='%Y-%m-%d %H:%M:%S')

class DestDB:
 Host = "192.168.1.10"
 DB = "spider"
 Table = "book_info"
 User = "test"
 Pwd = "123456"

def connect_db(host, db, user, pwd):
 conn = pymysql.connect(
  host=host,
  user=user,
  passwd=pwd,
  db=db,
  charset='utf8',
  connect_timeout=3600) #,
#  cursorclass=pymysql.cursors.DictCursor)
 conn.autocommit(True)
 return conn

def disconnect_db(conn, cursor):
 cursor.close()
 conn.close()

#提取評價人數(shù),如果評價人數(shù)少于10人,按10人處理
def hotratings(person):
 try:
  ptext = person.get_text().split()[0]
  pc = int(ptext[1:len(ptext)-4])
 except ValueError:
  pc = int(10)
 return pc

# 持久化到數(shù)據(jù)庫
def save_to_db(tag, book_reslist):
 dest_conn = connect_db(DestDB.Host, DestDB.DB, DestDB.User, DestDB.Pwd)
 dest_cursor = dest_conn.cursor()

 isql = "insert ignore into book_info "
 isql += "(`bookid`,`tag`,`author`,`translator`,`bookname`,`subname`,`press`,"
 isql += "`publishAt`,`price_str`,`stars`,`hotcnt`,`bookdesc`) values "
 isql += ",".join(["(%s)" % ",".join(['%s']*12)]*len(book_reslist))

 values = []
 for row in book_reslist:
  # 暫時將md5(bookname+author)作為bookid唯一指
  bookid = md5(("%s_%s"%(row[0],row[2])).encode('utf-8')).hexdigest()
  values.extend([bookid, tag]+row[:10])

 dest_cursor.execute(isql, tuple(values))
 disconnect_db(dest_conn, dest_cursor)

# 處理每一次訪問的頁面
def do_parse(tag, url):
 page_data = requests.get(url)
 soup = BeautifulSoup(page_data.text.encode("utf-8"), "lxml")
 # 提取標(biāo)簽信息
 tag = url.split("?")[0].split("/")[-1]
 # 抓取作者,出版社信息
 details = soup.select("#subject_list > ul > li > div.info > div.pub")
 # 抓取評分
 scores = soup.select("#subject_list > ul > li > div.info > div.star.clearfix > span.rating_nums")
 # 抓取評價人數(shù)
 persons = soup.select("#subject_list > ul > li > div.info > div.star.clearfix > span.pl")
 # 抓取書名
 booknames = soup.select("#subject_list > ul > li > div.info > h2 > a")
 # 抓取簡介 
 descs = soup.select("#subject_list > ul > li > div.info > p")
 # 從標(biāo)簽信息中分離內(nèi)容
 book_reslist = []
 for detail, score, personCnt, bookname, desc in zip(details, scores, persons, booknames, descs):
  try:
   subtitle = ""
   title_strs = [s.replace('\n', '').strip() for s in bookname.strings]
   title_strs = [s for s in title_strs if s]
   # 部分書籍有二級書名
   if not title_strs:
    continue
   elif len(title_strs) >= 2:
    bookname, subtitle = title_strs[:2]
   else:
    bookname = title_strs[0]

   # 評分人數(shù)
   hotcnt = hotratings(personCnt)
   desc = desc.get_text()
   stars = float('%.1f' % float(score.get_text() if score.get_text() else "-1"))

   author, translator, press, publishAt, price = [""]*5
   detail_texts = detail.get_text().replace('\n', '').split("/")
   detail_texts = [s.strip() for s in detail_texts]

   # 部分書籍無譯者信息
   if len(detail_texts) == 4:
    author, press, publishAt, price = detail_texts[:4]
   elif len(detail_texts) >= 5:
    author, translator, press, publishAt, price = detail_texts[:5]
   else:
    continue

   # 轉(zhuǎn)換出版日期為date類型
   if re.match('^[\d]{4}-[\d]{1,2}', publishAt):
    dts = publishAt.split('-')
    publishAt = datetime.date(int(dts[0]), int(dts[1]), 1)
   else:
    publishAt = datetime.date(1000, 1, 1)

   book_reslist.append([author, translator, bookname, subtitle, press, 
         publishAt, price, stars, hotcnt, desc])
  except Exception as e:
   logging.error(e)

 logging.info("insert count: %d" % len(book_reslist))
 if len(book_reslist) > 0:
  save_to_db(tag, book_reslist)
  book_reslist = []
 return len(details)

def main():
 with open("book_tags.txt") as fd:
  tags = fd.readlines()
  for tag in tags:
   tag = tag.strip()
   logging.info("current tag url: %s" % tag)
   for idx in range(0, 1000000, 20):
    try:
     url = "%s?start=%d&type=T" % (tag.strip(), idx)
     cnt = do_parse(tag.split('/')[-1], url)
     if cnt < 10:
      break
     # 睡眠若干秒,降低訪問頻率
     time.sleep(random.randint(10, 15))
    except Exception as e:
     logging.warn("outer_err: %s" % e)
   time.sleep(300)

if __name__ == "__main__":
 main()

小結(jié)

以上代碼基于python3環(huán)境來運(yùn)行;
需要首先安裝BeautifulSoup: pip install bs4
爬取過程中需要控制好訪問頻率;
需要對一些信息進(jìn)行異常處理,比如譯者信息、評論人數(shù)等。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python+OpenCV圖像處理之直方圖統(tǒng)計(jì)

    Python+OpenCV圖像處理之直方圖統(tǒng)計(jì)

    直方圖就是對圖像的另外一種解釋,它描述了整幅圖像的灰度分布。通過直方圖我們可以對圖像的亮度、灰度分布、對比度等有了一個直觀的認(rèn)識。本文將為大家詳細(xì)介紹一下如何通過OpenCV實(shí)現(xiàn)直方圖統(tǒng)計(jì),感興趣的可以了解一下
    2021-12-12
  • 教你使用Python的pygame模塊實(shí)現(xiàn)拼圖游戲

    教你使用Python的pygame模塊實(shí)現(xiàn)拼圖游戲

    pygame模塊是一個可以跨平臺的模塊,其設(shè)計(jì)目的就是為電子游戲而設(shè)計(jì),能夠支持圖片和聲音,下面這篇文章主要給給大家介紹了關(guān)于使用Python的pygame模塊實(shí)現(xiàn)拼圖游戲的相關(guān)資料,需要的朋友可以參考下
    2022-07-07
  • 如何利用Opencv實(shí)現(xiàn)圖像的加密解密

    如何利用Opencv實(shí)現(xiàn)圖像的加密解密

    一般情況下,圖像的加密和解密過程是通過按位異或運(yùn)算實(shí)現(xiàn)的,下面這篇文章主要給大家介紹了關(guān)于如何利用Opencv實(shí)現(xiàn)圖像加密解密的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2021-10-10
  • Python時間處理模塊Time和DateTime

    Python時間處理模塊Time和DateTime

    這篇文章主要為大家介紹了Python時間處理模塊Time和DateTime使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-06-06
  • Python基本運(yùn)算幾何運(yùn)算處理數(shù)字圖像示例

    Python基本運(yùn)算幾何運(yùn)算處理數(shù)字圖像示例

    這篇文章主要介紹了Python基本運(yùn)算,同個幾個幾何運(yùn)算處理數(shù)字圖像示例來為大家詳細(xì)講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2021-09-09
  • Python中的axis參數(shù)的具體使用

    Python中的axis參數(shù)的具體使用

    在我們使用Python中的Numpy和Pandas進(jìn)行數(shù)據(jù)分析的時候,經(jīng)常會遇到axis參數(shù),本文就來介紹一下axis參數(shù)的具體使用,感興趣的可以了解一下
    2021-12-12
  • 使用python搭建Django應(yīng)用程序步驟及版本沖突問題解決

    使用python搭建Django應(yīng)用程序步驟及版本沖突問題解決

    這篇文章主要介紹了使用python搭建Django應(yīng)用程序的步驟,最近還解決了因版本沖突出現(xiàn)的錯誤
    2013-11-11
  • python進(jìn)程間數(shù)據(jù)交互的幾種實(shí)現(xiàn)方式

    python進(jìn)程間數(shù)據(jù)交互的幾種實(shí)現(xiàn)方式

    本文主要介紹了python進(jìn)程數(shù)據(jù)交互的幾種實(shí)現(xiàn)方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05
  • 簡單介紹Python的Tornado框架中的協(xié)程異步實(shí)現(xiàn)原理

    簡單介紹Python的Tornado框架中的協(xié)程異步實(shí)現(xiàn)原理

    這篇文章主要介紹了簡單介紹Python的Tornado框架中的協(xié)程異步實(shí)現(xiàn)原理,作者基于Python的生成器講述了Tornado異步的特點(diǎn),需要的朋友可以參考下
    2015-04-04
  • 用python實(shí)現(xiàn)前向分詞最大匹配算法的示例代碼

    用python實(shí)現(xiàn)前向分詞最大匹配算法的示例代碼

    這篇文章主要介紹了用python實(shí)現(xiàn)前向分詞最大匹配算法的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08

最新評論

论坛| 临朐县| 万年县| 吉林市| 东丰县| 荥经县| 桓台县| 太和县| 沐川县| 宁乡县| 淮阳县| 盱眙县| 阿克陶县| 闸北区| 建德市| 定兴县| 华阴市| 永仁县| 叶城县| 凤凰县| 甘孜县| 舟山市| 新丰县| 饶平县| 馆陶县| 韶山市| 德江县| 滦平县| 无为县| 马公市| 鄂伦春自治旗| 荔波县| 隆回县| 清新县| 萍乡市| 三亚市| 雅江县| 淮南市| 金山区| 罗甸县| 昌图县|