Skip to content

Commit

Permalink
week1
Browse files Browse the repository at this point in the history
  • Loading branch information
huhuhang committed Nov 13, 2018
1 parent 1ba47e8 commit 29aa2da
Show file tree
Hide file tree
Showing 15 changed files with 375 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,4 @@ venv.bak/

# mypy
.mypy_cache/
.DS_Store
Binary file added mindmaps/week1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions week1-challenge-01/read_challenge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import pandas as pd

def convert(file):
df = pd.read_json(file)
df1000 = df[:1000]
df1000.to_hdf('user_study.h5', key='data')
14 changes: 14 additions & 0 deletions week1-challenge-02/sql_challenge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import sqlite3
import pandas as pd

def count(file, user_id):

sql_con = sqlite3.connect(file)
sql_query = "SELECT * FROM data WHERE user_id == {}".format(user_id)
df = pd.read_sql(sql_query, sql_con)

if len(df)==0:
return 0
else:
sum_minutes = df.minutes.sum()
return sum_minutes
21 changes: 21 additions & 0 deletions week1-challenge-03/github_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import requests
import pandas as pd

def issues(repo):
url = "https://api.github.com/repos/{}/issues".format(repo)
issues = requests.get(url)

issues_list = []
for issue in issues.json():
issues_dict = {'number':issue['number'],
'title':issue['title'],
'user_name':issue['user']['login']}
issues_list.append(issues_dict)

issues_df = pd.DataFrame(issues_list)

return issues_df

issues("numpy/numpy")


20 changes: 20 additions & 0 deletions week1-challenge-04/shiyanlou_user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import requests
from lxml import html


def user_info(user_id):

url = "https://www.shiyanlou.com/user/{}/".format(user_id)
content = requests.get(url)

if content.status_code == 200:
tree = html.fromstring(content.text)
user_name = tree.xpath('//span[@class="username"]/text()')[0]
user_level = tree.xpath('//span[@class="user-level"]/text()')[0][1:]
join_date = tree.xpath('//span[@class="join-date"]/text()')[0][:10]
return user_name, int(user_level), join_date
else:
user_name, user_level, join_date = (None, None, None)
return user_name, user_level, join_date


11 changes: 11 additions & 0 deletions week1-challenge-05/shiyanlou/scrapy.cfg
Original file line number Diff line number Diff line change
@@ -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 = shiyanlou.settings

[deploy]
#url = http://localhost:6800/
project = shiyanlou
Empty file.
15 changes: 15 additions & 0 deletions week1-challenge-05/shiyanlou/shiyanlou/items.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# -*- 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 ShiyanlouItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
repo_name = scrapy.Field() # repo 名称
update_time = scrapy.Field() # 更新时间
103 changes: 103 additions & 0 deletions week1-challenge-05/shiyanlou/shiyanlou/middlewares.py
Original file line number Diff line number Diff line change
@@ -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 ShiyanlouSpiderMiddleware(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 ShiyanlouDownloaderMiddleware(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)
28 changes: 28 additions & 0 deletions week1-challenge-05/shiyanlou/shiyanlou/pipelines.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# -*- 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
import pandas as pd

class ShiyanlouPipeline(object):

def process_item(self, item, spider):
# 读取 item 数据
repo_name = item['repo_name']
update_time = item['update_time']
# 每条数据组成临时 df_temp
df_temp = pd.DataFrame([[repo_name, update_time]], columns=['repo_name', 'update_time'])
# 将 df_temp 合并到 df
self.df = self.df.append(df_temp, ignore_index=True).sort_values(by=['update_time'], ascending=False)

#当爬虫启动时
def open_spider(self, spider):
# 新建一个带列名的空白 df
self.df = pd.DataFrame(columns=['repo_name', 'update_time'])

# 当爬虫关闭时
def close_spider(self, spider):
# 将 df 存储为 csv 文件
pd.DataFrame.to_csv(self.df, "../shiyanlou_repo.csv")
90 changes: 90 additions & 0 deletions week1-challenge-05/shiyanlou/shiyanlou/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# -*- coding: utf-8 -*-

# Scrapy settings for shiyanlou 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 = 'shiyanlou'

SPIDER_MODULES = ['shiyanlou.spiders']
NEWSPIDER_MODULE = 'shiyanlou.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'shiyanlou (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# 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 = {
# 'shiyanlou.middlewares.ShiyanlouSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'shiyanlou.middlewares.ShiyanlouDownloaderMiddleware': 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 = {
'shiyanlou.pipelines.ShiyanlouPipeline': 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'
4 changes: 4 additions & 0 deletions week1-challenge-05/shiyanlou/shiyanlou/spiders/__init__.py
Original file line number Diff line number Diff line change
@@ -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.
31 changes: 31 additions & 0 deletions week1-challenge-05/shiyanlou/shiyanlou/spiders/github.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# -*- coding: utf-8 -*-
import scrapy
from shiyanlou.items import ShiyanlouItem

"""
手动获取下一页爬虫
"""

class GithubSpider(scrapy.Spider):
name = 'github'
allowed_domains = ['github.com']

@property
def start_urls(self):
url_temp = 'https://github.com/shiyanlou?after={}&tab=repositories'
after = [
'',
'Y3Vyc29yOnYyOpK5MjAxNy0wNi0wNlQxNzozNjoxNSswODowMM4FkpW2',
'Y3Vyc29yOnYyOpK5MjAxNS0wMS0yM1QxNDoxODoyMSswODowMM4By2VI',
'Y3Vyc29yOnYyOpK5MjAxNC0xMS0xOVQxMDoxMDoyMyswODowMM4BmcsV',
]
return (url_temp.format(i) for i in after) # 1-4 页

def parse(self, response):
repos = response.xpath('//li[@itemprop="owns"]')
for repo in repos:
item = ShiyanlouItem()
item['repo_name'] = repo.xpath("./div/h3/a/text()").extract_first().strip()
item['update_time'] = repo.xpath("./div/relative-time/@datetime").extract_first()

yield item
31 changes: 31 additions & 0 deletions week1-challenge-05/shiyanlou/shiyanlou/spiders/github_next_page.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# -*- coding: utf-8 -*-
import scrapy
from shiyanlou.items import ShiyanlouItem

"""
自动获取下一页爬虫
"""

class GithubSpider(scrapy.Spider):
name = 'github_next_page'
allowed_domains = ['github.com']

@property
def start_urls(self):
return ('https://github.com/shiyanlou?tab=repositories', )

def parse(self, response):
repos = response.xpath('//li[@itemprop="owns"]')
for repo in repos:
item = ShiyanlouItem()
item['repo_name'] = repo.xpath("./div/h3/a/text()").extract_first().strip()
item['update_time'] = repo.xpath('./div/relative-time/@datetime').extract_first()

yield item

# 如果 Next 按钮没被禁用,那么表示有下一页
spans = response.css('div.pagination span.disabled::text')
if len(spans) == 0 or spans[-1].extract() != 'Next':
next_url = response.css(
'div.pagination a:last-child::attr(href)').extract_first()
yield response.follow(next_url, callback=self.parse)

0 comments on commit 29aa2da

Please sign in to comment.