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

Python多線程爬取豆瓣影評API接口

 更新時間:2019年10月22日 09:14:40   作者:Python小老弟  
這篇文章主要介紹了Python多線程爬取豆瓣影評API接口,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

爬蟲庫

使用簡單的requests庫,這是一個阻塞的庫,速度比較慢。

解析使用XPATH表達式

總體采用類的形式

多線程

使用concurrent.future并發(fā)模塊,建立線程池,把future對象扔進去執(zhí)行即可實現(xiàn)并發(fā)爬取效果

數(shù)據(jù)存儲

使用Python ORM sqlalchemy保存到數(shù)據(jù)庫,也可以使用自帶的csv模塊存在CSV中。

API接口

因為API接口存在數(shù)據(jù)保護情況,一個電影的每一個分類只能抓取前25頁,全部評論、好評、中評、差評所有分類能爬100頁,每頁有20個數(shù)據(jù),即最多為兩千條數(shù)據(jù)。

因為時效性原因,不保證代碼能爬到數(shù)據(jù),只是給大家一個參考思路,上代碼:

from datetime import datetime
import random
import csv
from concurrent.futures import ThreadPoolExecutor, as_completed

from lxml import etree
import pymysql
import requests

from models import create_session, Comments

#隨機UA
USERAGENT = [
  'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1',
  'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36',
  'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0',
  'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
  'Opera/9.80 (Windows NT 6.1; U; zh-cn) Presto/2.9.168 Version/11.50',
  'Mozilla/5.0 (Windows; U; Windows NT 6.1; ) AppleWebKit/534.12 (KHTML, like Gecko) Maxthon/3.0 Safari/534.12'
]


class CommentFetcher:
  headers = {'User-Agent': ''}
  cookie = ''
  cookies = {'cookie': cookie}
  # cookie為登錄后的cookie,需要自行復(fù)制
  base_node = '//div[@class="comment-item"]'


  def __init__(self, movie_id, start, type=''):
    '''
    :type: 全部評論:'', 好評:h 中評:m 差評:l
    :movie_id: 影片的ID號
    :start: 開始的記錄數(shù),0-480
    '''
    self.movie_id = movie_id
    self.start = start
    self.type = type
    self.url = 'https://movie.douban.com/subject/{id}/comments?start={start}&limit=20&sort=new_score\&status=P&percent_type={type}&comments_only=1'.format(
      id=str(self.movie_id),
      start=str(self.start),
      type=self.type
    )
    #創(chuàng)建數(shù)據(jù)庫連接
    self.session = create_session()

  #隨機useragent
  def _random_UA(self):
    self.headers['User-Agent'] = random.choice(USERAGENT)


  #獲取api接口,使用get方法,返回的數(shù)據(jù)為json數(shù)據(jù),需要提取里面的HTML
  def _get(self):
    self._random_UA()
    res = ''
    try:
      res = requests.get(self.url, cookies=self.cookies, headers=self.headers)
      res = res.json()['html']
    except Exception as e:
      print('IP被封,請使用代理IP')
    print('正在獲取{} 開始的記錄'.format(self.start))
    return res

  def _parse(self):
    res = self._get()
    dom = etree.HTML(res)

    #id號
    self.id = dom.xpath(self.base_node + '/@data-cid')
    #用戶名
    self.username = dom.xpath(self.base_node + '/div[@class="avatar"]/a/@title')
    #用戶連接
    self.user_center = dom.xpath(self.base_node + '/div[@class="avatar"]/a/@href')
    #點贊數(shù)
    self.vote = dom.xpath(self.base_node + '//span[@class="votes"]/text()')
    #星級
    self.star = dom.xpath(self.base_node + '//span[contains(@class,"rating")]/@title')
    #發(fā)表時間
    self.time = dom.xpath(self.base_node + '//span[@class="comment-time "]/@title')
    #評論內(nèi)容 所有span標簽class名為short的節(jié)點文本
    self.content = dom.xpath(self.base_node + '//span[@class="short"]/text()')

  #保存到數(shù)據(jù)庫
  def save_to_database(self):
    self._parse()
    for i in range(len(self.id)):
      try:
        comment = Comments(
          id=int(self.id[i]),
          username=self.username[i],
          user_center=self.user_center[i],
          vote=int(self.vote[i]),
          star=self.star[i],
          time=datetime.strptime(self.time[i], '%Y-%m-%d %H:%M:%S'),
          content=self.content[i]
        )

        self.session.add(comment)
        self.session.commit()
        return 'finish'


      except pymysql.err.IntegrityError as e:
        print('數(shù)據(jù)重復(fù),不做任何處理')

      except Exception as e:
        #數(shù)據(jù)添加錯誤,回滾
        self.session.rollback()

      finally:
        #關(guān)閉數(shù)據(jù)庫連接
        self.session.close()

  #保存到csv
  def save_to_csv(self):
    self._parse()
    f = open('comment.csv', 'w', encoding='utf-8')
    csv_in = csv.writer(f, dialect='excel')
    for i in range(len(self.id)):
      csv_in.writerow([
        int(self.id[i]),
        self.username[i],
        self.user_center[i],
        int(self.vote[i]),
        self.time[i],
        self.content[i]
      ])
    f.close()


if __name__ == '__main__':
  with ThreadPoolExecutor(max_workers=4) as executor:
    futures = []
    for i in ['', 'h', 'm', 'l']:
      for j in range(25):
        fetcher = CommentFetcher(movie_id=26266893, start=j * 20, type=i)
        futures.append(executor.submit(fetcher.save_to_csv))

    for f in as_completed(futures):
      try:
        res = f.done()
        if res:
          ret_data = f.result()
          if ret_data == 'finish':
            print('{} 成功保存數(shù)據(jù)'.format(str(f)))
      except Exception as e:
        f.cancel()

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

相關(guān)文章

  • Python實現(xiàn)批量提取Word中的表格

    Python實現(xiàn)批量提取Word中的表格

    表格在word文檔中常見的文檔元素之一,操作word文件時有時需要提取文件中多個表格的內(nèi)容到一個新的文件,本文給大家分享兩種批量提取文檔中表格的兩種方法,希望對大家有所幫助
    2024-02-02
  • python/sympy求解矩陣方程的方法

    python/sympy求解矩陣方程的方法

    今天小編就為大家分享一篇python/sympy求解矩陣方程的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11
  • pyqt5簡介及安裝方法介紹

    pyqt5簡介及安裝方法介紹

    這篇文章主要介紹了pyqt5簡介及安裝方法介紹,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下
    2018-01-01
  • 對python中的控制條件、循環(huán)和跳出詳解

    對python中的控制條件、循環(huán)和跳出詳解

    今天小編就為大家分享一篇對python中的控制條件、循環(huán)和跳出詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-06-06
  • 基于python的文字轉(zhuǎn)圖片工具示例詳解

    基于python的文字轉(zhuǎn)圖片工具示例詳解

    這篇文章主要介紹了基于python的文字轉(zhuǎn)圖片工具,請求示例是使用?curl?命令請求示例,本文給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧
    2024-08-08
  • 最好的Python DateTime 庫之 Pendulum 長篇解析

    最好的Python DateTime 庫之 Pendulum 長篇解析

    datetime 模塊是 Python 中最重要的內(nèi)置模塊之一,它為實際編程問題提供許多開箱即用的解決方案,非常靈活和強大。例如,timedelta 是我最喜歡的工具之一
    2021-11-11
  • python五子棋游戲的設(shè)計與實現(xiàn)

    python五子棋游戲的設(shè)計與實現(xiàn)

    這篇文章主要為大家詳細介紹了python五子棋游戲的設(shè)計與實現(xiàn),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-06-06
  • Pandas.DataFrame重置列的行名實現(xiàn)(set_index)

    Pandas.DataFrame重置列的行名實現(xiàn)(set_index)

    本文主要介紹了Pandas.DataFrame重置列的行名實現(xiàn)(set_index),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-02-02
  • Pandas導(dǎo)入導(dǎo)出excel、csv、txt文件教程

    Pandas導(dǎo)入導(dǎo)出excel、csv、txt文件教程

    Pandas?是一個強大的數(shù)據(jù)分析和處理庫,可以用來讀取和處理多種數(shù)據(jù)格式,本文主要介紹了Pandas導(dǎo)入導(dǎo)出excel、csv、txt文件教程,具有一定的參考價值,感興趣的可以了解一下
    2024-04-04
  • Python編程中運用閉包時所需要注意的一些地方

    Python編程中運用閉包時所需要注意的一些地方

    這篇文章主要介紹了Python編程中運用閉包時所需要注意的一些地方,文章來自國內(nèi)知名的Python開發(fā)者felinx的博客,需要的朋友可以參考下
    2015-05-05

最新評論

重庆市| 高安市| 九龙坡区| 海口市| 浦江县| 建昌县| 胶南市| 云和县| 乌兰浩特市| 汽车| 灯塔市| 昂仁县| 邵阳县| 浑源县| 手游| 新营市| 阳山县| 广安市| 上杭县| 蓬溪县| 四会市| 东乡| 股票| 桐城市| 济宁市| 南华县| 水富县| 科尔| 镶黄旗| 榆林市| 玉田县| 阿拉善右旗| 凤城市| 太谷县| 晋宁县| 南江县| 明光市| 谢通门县| 尤溪县| 阿尔山市| 阳山县|