Py学习  »  Python

用python在爱奇艺官网抓取 '楚乔传' 评论

大数据挖掘DT数据分析 • 8 年前 • 1073 次点击  



大数据挖掘DT数据分析  公众号: datadw



1. config


[python] view plain copy

  1. MONGO_URL = 'localhost'  

  2. MONGO_DB = 'iqiyi'  

  3. MONGO_TABLE = 'iqy_comments'  

  4.   

  5.   

  6. SERVICE_ARGS = ['--load-images=false''--disk-cache=true']  

  7.   

  8. CIRCLE = 50  


2. spider

[python] view plain copy

  1. import pymongo  

  2. import time  

  3. import datetime  

  4.   

  5. from pyquery import PyQuery as pq  

  6.   

  7. from selenium import webdriver  

  8. from selenium.webdriver.support.ui import WebDriverWait  

  9. from selenium.webdriver.support import expected_conditions as EC  

  10. from selenium.webdriver.common.by import By  

  11. from CommentSpider.Config import *  

  12.   

  13. # db  

  14. client = pymongo.MongoClient(MONGO_URL)  

  15. db = client[MONGO_DB]  

  16.   

  17. # driver  

  18. # chrome_options = webdriver.ChromeOptions()  

  19. # chrome_options.add_argument('--headless')  

  20. # chrome_options.add_argument('--disable-gpu')  

  21. # browser = webdriver.Chrome(chrome_options=chrome_options,executable_path='D:\\ProgramData\\Anaconda3\\Scripts\\chromedriver')  

  22.   

  23. # browser = webdriver.Chrome()  

  24.   

  25. browser = webdriver.PhantomJS(service_args=SERVICE_ARGS)  

  26. browser.set_window_size(1400900)  

  27.   

  28. wait = WebDriverWait(browser, 15)  

  29.   

  30. # time  

  31. now = datetime.date.today()  

  32. one_day = datetime.timedelta(days=1)  

  33. today = now.strftime('%m-%d')  

  34. yesterday = (now - one_day).strftime('%m-%d')  

  35.   

  36. def save_to_mongo(result):  

  37.     try:  

  38.         if db[MONGO_TABLE].find(result).limit(1).count() == 0:  

  39.             db[MONGO_TABLE].insert(result)  

  40.         else:  

  41.             print('comment duplicate')  

  42.     except Exception:  

  43.         print('mongodb error')  

  44.   

  45. def get_comments(page_num):  

  46.     if page_num > CIRCLE:  

  47.         return  

  48.     print('page_num:', page_num)  

  49.     html = browser.page_source  

  50.     doc = pq(html)  

  51.     for i in range(5 + page_num * 2024 + page_num * 20):  

  52.         try:  

  53.             #  在这已经结束程序  

  54.             item = doc.find('#qitancommonarea > div:nth-child(2) > div > div > div > '  

  55.                             'div:nth-child(2) > div > div:nth-child({})'.format(i))  

  56.         except Exception:  

  57.             return  

  58.   

  59.         c_time = item.find('.csPpFeed_time').text()  

  60.         if '昨日' in c_time:  

  61.             c_time = yesterday  

  62.         elif '前' in c_time:  

  63.             c_time = today  

  64.         else:  

  65.             c_time = c_time  

  66.   

  67.         comment = {  

  68.             'time' : c_time,  

  69.             'name': item.find('.csPpFeed_master').text(),  

  70.             'img_url': item.find('.csPpFeed_section > .section_hd > a > img').attr('data-lazy'),  

  71.             'user_url': item.find('.csPpFeed_master').attr('href'),  

  72.             'ft_love': item.find('.csPpFeed_ftLove > .ftNums').attr('data-paopao-agreecnt'),  

  73.             'ft_comment': item.find('.csPpFeed_ftComment > .ftNums').attr('data-paopao-commentcnt'),  

  74.             'comment': item.find('.csPpFeed_des > span').text()  

  75.         }  

  76.         # print(i, comment)  

  77.         # 保存到mongodb + 去重  

  78.         save_to_mongo(result=comment)  

  79.   

  80.     # 加载更多  

  81.     more = wait.until(  

  82.         EC.element_to_be_clickable(  

  83.             (By.CSS_SELECTOR, '#qitancommonarea > div:nth-child(2) > div > div > div > div:nth-child(2)'  

  84.                               '> div > div.csPpFeed_list > div > div > a')  

  85.         )  

  86.     )  

  87.     more.click()  

  88.     sleep()  

  89.     page_num += 1  

  90.     wait.until(  

  91.         EC.text_to_be_present_in_element(  

  92.             (By.CSS_SELECTOR, '#qitancommonarea > div:nth-child(2) > div > div > div > div:nth-child(2)'  

  93.                               '> div > div.csPpFeed_list > div > div > a'), '加载更多'  

  94.         )  

  95.     )  

  96.     get_comments(page_num=page_num)  

  97.   

  98.   

  99. def start(url):  

  100.     print('url:', url)  

  101.     browser.get(url=url)  

  102.   

  103.     browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')  # 底部  

  104.     sleep()  

  105.     wait.until(  

  106.         EC.presence_of_element_located(  

  107.             (By.CSS_SELECTOR, '#qitancommonarea > div:nth-child(2) > div > div > '  

  108.                               'div > div:nth-child(2) > div > div:nth-child({})'.format(24))  

  109.         )  

  110.     )  # 等待评论加载出来  

  111.     get_comments(page_num=0)  

  112.   

  113. def sleep():  

  114.     time.sleep(3)  

  115.   

  116. def stop_vedio():  

  117.     switch = wait.until(  

  118.         EC.element_to_be_clickable(  

  119.             (By.CSS_SELECTOR,  

  120.              '#flashbox > div.pw-video > div:nth-child(5) > div.bottom-public > a.bottom-public_play > i')  

  121.         )  

  122.     )  

  123.     switch.click()  

  124.   

  125. if __name__ == '__main__':  

  126.     # 400次循环  

  127.     # 50次 加载更多  

  128.     start(url='http://www.iqiyi.com/v_19rr6z41d8.html')  

http://blog.csdn.net/peerslee/article/details/73928077


人工智能大数据与深度学习

搜索添加微信公众号:weic2c


长按图片,识别二维码,点关注



大数据挖掘DT数据分析

搜索添加微信公众号:datadw


教你机器学习,教你数据挖掘


长按图片,识别二维码,点关注


今天看啥 - 高品质阅读平台
本文地址:http://www.jintiankansha.me/t/cXkVmPBnwK
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/3769