diff --git a/spiders.yml b/spiders.yml new file mode 100644 index 0000000..e2c3719 --- /dev/null +++ b/spiders.yml @@ -0,0 +1,63 @@ +name: scrapy +channels: + - defaults +dependencies: + - appdirs=1.4.3=py37h28b3542_0 + - asn1crypto=0.24.0=py37_0 + - atomicwrites=1.3.0=py37_1 + - attrs=19.1.0=py37_1 + - automat=0.7.0=py37_0 + - ca-certificates=2019.1.23=0 + - certifi=2019.3.9=py37_0 + - cffi=1.12.2=py37hb5b8e2f_1 + - constantly=15.1.0=py37h28b3542_0 + - cryptography=2.6.1=py37ha12b0ac_0 + - cssselect=1.0.3=py37_0 + - hyperlink=18.0.0=py37_0 + - icu=58.2=h4b95b61_1 + - idna=2.8=py37_0 + - incremental=17.5.0=py37_0 + - libcxx=4.0.1=hcfea43d_1 + - libcxxabi=4.0.1=hcfea43d_1 + - libedit=3.1.20181209=hb402a30_0 + - libffi=3.2.1=h475c297_4 + - libiconv=1.15=hdd342a3_7 + - libxml2=2.9.9=hab757c2_0 + - libxslt=1.1.33=h33a18ac_0 + - lxml=4.3.2=py37hef8c89e_0 + - more-itertools=6.0.0=py37_0 + - ncurses=6.1=h0a44026_1 + - openssl=1.1.1b=h1de35cc_1 + - parsel=1.5.1=py37_0 + - pip=19.0.3=py37_0 + - pluggy=0.9.0=py37_0 + - py=1.8.0=py37_0 + - pyasn1=0.4.5=py_0 + - pyasn1-modules=0.2.4=py37_0 + - pycparser=2.19=py37_0 + - pydispatcher=2.0.5=py37_1 + - pyhamcrest=1.9.0=py37_2 + - pyopenssl=19.0.0=py37_0 + - pysocks=1.7.0=py37_0 + - pytest=4.4.0=py37_1 + - pytest-runner=4.4=py_0 + - python=3.7.3=h359304d_0 + - queuelib=1.5.0=py37_0 + - readline=7.0=h1de35cc_5 + - scrapy=1.5.2=py37_0 + - selenium=3.141.0=py37h1de35cc_0 + - service_identity=18.1.0=py37h28b3542_0 + - setuptools=41.0.0=py37_0 + - six=1.12.0=py37_0 + - sqlite=3.27.2=ha441bb4_0 + - tk=8.6.8=ha441bb4_0 + - twisted=18.9.0=py37h1de35cc_0 + - urllib3=1.25.2=py37_0 + - w3lib=1.20.0=py37_0 + - wheel=0.33.1=py37_0 + - xz=5.2.4=h1de35cc_4 + - zlib=1.2.11=h1de35cc_3 + - zope=1.0=py37_1 + - zope.interface=4.6.0=py37h1de35cc_0 +prefix: /Users/huy/miniconda3/envs/scrapy + diff --git a/study163/docker-compose.yml b/study163/docker-compose.yml new file mode 100644 index 0000000..8538b89 --- /dev/null +++ b/study163/docker-compose.yml @@ -0,0 +1,12 @@ +version: '3' +services: + selenium-chrome: + container_name: selenium-chrome-study-163 + image: selenium/standalone-chrome-debug:3.141.59-neon + environment: + - VNC_NO_PASSWORD=1 + volumes: + - /dev/shm:/dev/shm + ports: + - 4444:4444 + - 15900:5900 \ No newline at end of file diff --git a/study163/scrapy.cfg b/study163/scrapy.cfg new file mode 100644 index 0000000..ac6d266 --- /dev/null +++ b/study163/scrapy.cfg @@ -0,0 +1,11 @@ +# Automatically created by: scrapy startproject +# +# For more information about the [deploy] section see: +# https://scrapyd.readthedocs.io/en/latest/deploy.html + +[settings] +default = study163.settings + +[deploy] +#url = http://localhost:6800/ +project = study163 diff --git a/study163/study163/__init__.py b/study163/study163/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/study163/study163/common/SeleniumSpider.py b/study163/study163/common/SeleniumSpider.py new file mode 100644 index 0000000..6ac31d1 --- /dev/null +++ b/study163/study163/common/SeleniumSpider.py @@ -0,0 +1,38 @@ +import logging +import os + +from scrapy.spiders import Spider +from selenium import webdriver +from selenium.webdriver.remote.webdriver import WebDriver + + +class SeleniumSpider(Spider): + + browser: WebDriver + + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.URL_TEMPLATE = 'http://{REMOTE_SELENIUM_ADDR}:4444/wd/hub' + self.USE_REMOTE_SELENIUM = os.getenv('USE_REMOTE_SELENIUM', 'FALSE') + self.REMOTE_SELENIUM_ADDR = os.getenv('REMOTE_SELENIUM_ADDR', '127.0.0.1') + self.PAGE_LOAD_TIME_OUT = 30 + self.browser = self.get_selenium_driver() + + def parse(self, response): + pass + + def closed(self, spider) -> None: + logging.info("shut down selenium") + self.browser.close() + + def get_selenium_driver(self) -> WebDriver: + if self.USE_REMOTE_SELENIUM == 'TRUE': + remote_selenium_url = self.URL_TEMPLATE.format(REMOTE_SELENIUM_ADDR=self.REMOTE_SELENIUM_ADDR) + driver = webdriver.Remote( + command_executor=remote_selenium_url, + desired_capabilities=webdriver.DesiredCapabilities.CHROME, + ) + driver.set_page_load_timeout(self.PAGE_LOAD_TIME_OUT) + return driver + else: + return webdriver.Chrome() diff --git a/study163/study163/common/__init__.py b/study163/study163/common/__init__.py new file mode 100644 index 0000000..03d2321 --- /dev/null +++ b/study163/study163/common/__init__.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python +""" +@author:shz +@license: Apache Licence +@file: __init__.py.py +@time: 2019/05/21 +@contact: sunhouzan@163.com +@site: +@software: PyCharm +""" + diff --git a/study163/study163/common/crawl.py b/study163/study163/common/crawl.py new file mode 100644 index 0000000..94a4421 --- /dev/null +++ b/study163/study163/common/crawl.py @@ -0,0 +1,12 @@ +from abc import abstractmethod + + +class CrawlStrategy: + + @classmethod + def version(self): + return "1.0" + + @abstractmethod + def crawl(self, spider, request): + raise NotImplementedError diff --git a/study163/study163/items.py b/study163/study163/items.py new file mode 100644 index 0000000..4e4fd3e --- /dev/null +++ b/study163/study163/items.py @@ -0,0 +1,14 @@ +# -*- coding: utf-8 -*- + +# Define here the models for your scraped items +# +# See documentation in: +# https://doc.scrapy.org/en/latest/topics/items.html + +import scrapy + + +class Study163Item(scrapy.Item): + # define the fields for your item here like: + # name = scrapy.Field() + pass diff --git a/study163/study163/main.py b/study163/study163/main.py new file mode 100644 index 0000000..1247675 --- /dev/null +++ b/study163/study163/main.py @@ -0,0 +1,3 @@ +from scrapy import cmdline + +cmdline.execute("scrapy crawl study163".split()) \ No newline at end of file diff --git a/study163/study163/middlewares.py b/study163/study163/middlewares.py new file mode 100644 index 0000000..8674235 --- /dev/null +++ b/study163/study163/middlewares.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- + +# Define here the models for your spider middleware +# +# See documentation in: +# https://doc.scrapy.org/en/latest/topics/spider-middleware.html + +from scrapy import signals + + +class Study163SpiderMiddleware(object): + # Not all methods need to be defined. If a method is not defined, + # scrapy acts as if the spider middleware does not modify the + # passed objects. + + @classmethod + def from_crawler(cls, crawler): + # This method is used by Scrapy to create your spiders. + s = cls() + crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) + return s + + def process_spider_input(self, response, spider): + # Called for each response that goes through the spider + # middleware and into the spider. + + # Should return None or raise an exception. + return None + + def process_spider_output(self, response, result, spider): + # Called with the results returned from the Spider, after + # it has processed the response. + + # Must return an iterable of Request, dict or Item objects. + for i in result: + yield i + + def process_spider_exception(self, response, exception, spider): + # Called when a spider or process_spider_input() method + # (from other spider middleware) raises an exception. + + # Should return either None or an iterable of Response, dict + # or Item objects. + pass + + def process_start_requests(self, start_requests, spider): + # Called with the start requests of the spider, and works + # similarly to the process_spider_output() method, except + # that it doesn’t have a response associated. + + # Must return only requests (not items). + for r in start_requests: + yield r + + def spider_opened(self, spider): + spider.logger.info('Spider opened: %s' % spider.name) + + +class Study163DownloaderMiddleware(object): + # Not all methods need to be defined. If a method is not defined, + # scrapy acts as if the downloader middleware does not modify the + # passed objects. + + @classmethod + def from_crawler(cls, crawler): + # This method is used by Scrapy to create your spiders. + s = cls() + crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) + return s + + def process_request(self, request, spider): + # Called for each request that goes through the downloader + # middleware. + + # Must either: + # - return None: continue processing this request + # - or return a Response object + # - or return a Request object + # - or raise IgnoreRequest: process_exception() methods of + # installed downloader middleware will be called + return None + + def process_response(self, request, response, spider): + # Called with the response returned from the downloader. + + # Must either; + # - return a Response object + # - return a Request object + # - or raise IgnoreRequest + return response + + def process_exception(self, request, exception, spider): + # Called when a download handler or a process_request() + # (from other downloader middleware) raises an exception. + + # Must either: + # - return None: continue processing this exception + # - return a Response object: stops process_exception() chain + # - return a Request object: stops process_exception() chain + pass + + def spider_opened(self, spider): + spider.logger.info('Spider opened: %s' % spider.name) diff --git a/study163/study163/pipelines.py b/study163/study163/pipelines.py new file mode 100644 index 0000000..0b4e4b6 --- /dev/null +++ b/study163/study163/pipelines.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- + +# Define your item pipelines here +# +# Don't forget to add your pipeline to the ITEM_PIPELINES setting +# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html + + +class Study163Pipeline(object): + def process_item(self, item, spider): + return item diff --git a/study163/study163/settings.py b/study163/study163/settings.py new file mode 100644 index 0000000..d9c13fd --- /dev/null +++ b/study163/study163/settings.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- + +# Scrapy settings for study163 project +# +# For simplicity, this file contains only settings considered important or +# commonly used. You can find more settings consulting the documentation: +# +# https://doc.scrapy.org/en/latest/topics/settings.html +# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html +# https://doc.scrapy.org/en/latest/topics/spider-middleware.html + +BOT_NAME = 'study163' + +SPIDER_MODULES = ['study163.spiders'] +NEWSPIDER_MODULE = 'study163.spiders' + +USER_NAME = '17388082976' +PASSWORD = '*' + + +# Crawl responsibly by identifying yourself (and your website) on the user-agent +#USER_AGENT = 'study163 (+http://www.yourdomain.com)' + +# Obey robots.txt rules +ROBOTSTXT_OBEY = True + +# Configure maximum concurrent requests performed by Scrapy (default: 16) +#CONCURRENT_REQUESTS = 32 + +# Configure a delay for requests for the same website (default: 0) +# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay +# See also autothrottle settings and docs +#DOWNLOAD_DELAY = 3 +# The download delay setting will honor only one of: +#CONCURRENT_REQUESTS_PER_DOMAIN = 16 +#CONCURRENT_REQUESTS_PER_IP = 16 + +# Disable cookies (enabled by default) +#COOKIES_ENABLED = False + +# Disable Telnet Console (enabled by default) +#TELNETCONSOLE_ENABLED = False + +# Override the default request headers: +#DEFAULT_REQUEST_HEADERS = { +# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', +# 'Accept-Language': 'en', +#} + +# Enable or disable spider middlewares +# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html +#SPIDER_MIDDLEWARES = { +# 'study163.middlewares.Study163SpiderMiddleware': 543, +#} + +# Enable or disable downloader middlewares +# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html +#DOWNLOADER_MIDDLEWARES = { +# 'study163.middlewares.Study163DownloaderMiddleware': 543, +#} + +# Enable or disable extensions +# See https://doc.scrapy.org/en/latest/topics/extensions.html +#EXTENSIONS = { +# 'scrapy.extensions.telnet.TelnetConsole': None, +#} + +# Configure item pipelines +# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html +#ITEM_PIPELINES = { +# 'study163.pipelines.Study163Pipeline': 300, +#} + +# Enable and configure the AutoThrottle extension (disabled by default) +# See https://doc.scrapy.org/en/latest/topics/autothrottle.html +#AUTOTHROTTLE_ENABLED = True +# The initial download delay +#AUTOTHROTTLE_START_DELAY = 5 +# The maximum download delay to be set in case of high latencies +#AUTOTHROTTLE_MAX_DELAY = 60 +# The average number of requests Scrapy should be sending in parallel to +# each remote server +#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 +# Enable showing throttling stats for every response received: +#AUTOTHROTTLE_DEBUG = False + +# Enable and configure HTTP caching (disabled by default) +# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings +#HTTPCACHE_ENABLED = True +#HTTPCACHE_EXPIRATION_SECS = 0 +#HTTPCACHE_DIR = 'httpcache' +#HTTPCACHE_IGNORE_HTTP_CODES = [] +#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' diff --git a/study163/study163/spiders/Study163Spider.py b/study163/study163/spiders/Study163Spider.py new file mode 100644 index 0000000..0886e09 --- /dev/null +++ b/study163/study163/spiders/Study163Spider.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +import time + +from scrapy.utils.project import get_project_settings +from selenium.webdriver.common.by import By +from selenium.webdriver.support import expected_conditions as EC +from selenium.webdriver.support.wait import WebDriverWait + +from study163.common.SeleniumSpider import SeleniumSpider + + +class Study163Spider(SeleniumSpider): + name: str = 'study163' + allowed_domains: list = ['study.163.com'] + start_url: str = 'https://study.163.com/member/login.htm' + + settings = None + + def __init__(self, *a, **kw): + super(Study163Spider, self).__init__(*a, **kw) + self.settings = get_project_settings() + + def start_requests(self): + self.browser.get(self.start_url) + try: + is_login_frame_present = WebDriverWait(self.browser, 20).until( + EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[contains(@src,'dl.reg.163.com')]")) + ) + if is_login_frame_present: + user_input = self.browser.find_element_by_xpath("//input[@name='email' and @type='tel']") + user_input.send_keys(self.settings.get('USER_NAME')) + pwd_input = self.browser.find_element_by_xpath("//input[@name='email' and @type='password']") + pwd_input.send_keys(self.settings.get('PASSWORD')) + self.browser.find_element_by_xpath("//a[@id='submitBtn']").click() + is_search_box_present = WebDriverWait(self.browser, 20).until( + EC.presence_of_element_located( + (By.XPATH, "//input[@type='text' and @class='j-input j-searchInput']")) + ) + time.sleep(2) + if is_search_box_present: + self.browser.get('https://study.163.com/course/courseMain.htm?courseId=1005359012') + WebDriverWait(self.browser, 30).until( + EC.element_to_be_clickable( + (By.XPATH, "//a[span[contains(text(),'继续学习')]]")) + ) + cont_stydy_btn_element = self.browser.find_element_by_xpath("//a[span[contains(text(),'继续学习')]]") + self.browser.execute_script('arguments[0].click();', cont_stydy_btn_element) + is_chap_list_present = WebDriverWait(self.browser, 20).until( + EC.presence_of_element_located( + (By.XPATH, "//div[@class='m-chapterList']")) + ) + if is_chap_list_present: + section_element_list = self.browser.find_elements_by_xpath("//div[contains(@class,'section')]") + lesson_idx_list = list(map(lambda section: section.get_attribute('data-lesson'), section_element_list)) + for lesson_idx in lesson_idx_list: + section = self.browser.find_element_by_xpath(f"//div[@data-lesson='{lesson_idx}']") + self.browser.execute_script('arguments[0].click();', section) + is_main_video_present = WebDriverWait(self.browser, 20).until( + EC.visibility_of_element_located( + (By.XPATH, "//div[contains(@class,'u-edu-h5player-mainvideo')]") + ) + ) + time.sleep(5) + if is_main_video_present: + print(f'Extracting {lesson_idx} url') + if lesson_idx == 3: + print('please wait here') + video_url = self.browser.find_element_by_xpath( + "//div[contains(@class,'u-edu-h5player-mainvideo')]" + ).find_element_by_xpath( + "//video/source" + ).get_attribute('src') + print(video_url) + else: + raise Exception(f'{self.start_url} is not loaded correctly.') + + + finally: + print('llllll') + + def parse(self, response): + pass diff --git a/study163/study163/spiders/__init__.py b/study163/study163/spiders/__init__.py new file mode 100644 index 0000000..ebd689a --- /dev/null +++ b/study163/study163/spiders/__init__.py @@ -0,0 +1,4 @@ +# This package will contain the spiders of your Scrapy project +# +# Please refer to the documentation for information on how to create and manage +# your spiders.