forked from qianxin/tumblr_imgs_download
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
64 lines (54 loc) · 1.68 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
#-*-coding:utf-8-*-
"""
通用程序
"""
import sys
import os
import requests
from mylogger import get_logger
dllog = get_logger("app")
try:
reload(sys)
sys.setdefaultencoding('utf-8')
except NameError:
# The only supported default encodings in Python are:
# Python 2.x: ASCII
# Python 3.x: UTF-8
# So no need to sys.setdefaultencoding('utf-8')
pass # py3
# 执行 requests 的数据下载
def download_page(url, ret_json=False, proxies=None):
if not url:
dllog.info("url should not be None")
return ''
try:
dllog.info("当前下载的 url: %s " % url)
r = requests.get(url, proxies=proxies, timeout=10)
if r.status_code == 200:
if ret_json:
return r.json()
# r.text is decoded string
# r.content is binary response content(bytes)
# see http://docs.python-requests.org/en/latest/user/quickstart/#binary-response-content
return r.text
else:
dllog.info("下载失败,status_code: %s" % r.status_code)
return ''
except Exception as e:
dllog.info("下载失败, %s %s" % (url, e))
return ''
def download_imgs(url, path, name, proxies=None):
try:
dllog.info("当前下载的 url: %s " % url)
r = requests.get(url, stream=True, proxies=proxies, timeout=10)
file = os.path.join(path, name)
with open(file, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
f.write(chunk)
except Exception as e:
dllog.info("下载失败, %s %s" % (url, e))
def test():
pass
if __name__ == "__main__":
test()