1、在亚马逊上查询图书的排名
from atexit import register
from re import compile
from threading import Thread
from time import ctime
import urllib3
import requests
# REGEX = compile(r'图书商品里排第([\d,]+)名')
REGEX = compile(r'#([\d,]+) in Books ')
AMZN = 'http://amazon.com/dp/'
ISBNs = {
'0132269937': 'Core Python Programming',
'0132356139': 'Python Web Development with Django',
'0137143419': 'Python Fundamentals',
'1593279280': 'Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming',
'1449355730': 'Learning Python, 5th Edition',
'1449359361': 'Introducing Python: Modern Computing in Simple Packages',
}
# https://www.amazon.com//dp/0132269937
def getRanking(isbn):
requests.packages.urllib3.disable_warnings()
http = urllib3.PoolManager()
r = http.request('GET', '%s%s' % (AMZN, isbn))
# print(r.status) # 200
# 获得html源码,utf-8解码
data = r.data.decode()
return REGEX.findall(data)[0]
def _showRanking(isbn):
print('- %r ranked %s' % (ISBNs[isbn], getRanking(isbn)))
def main():
print('At', ctime(), ' PDT on Amazon...')
for isbn in ISBNs:
Thread(target=_showRanking, args=(isbn,)).start()
# _showRanking(isbn)
@register
def _atexit():
print('all DONE at:', ctime())
if __name__ == '__main__':
main()
2、单线程执行结果
总共花费41秒,结果是按照字典顺序依次显示。
(py3) [root@nginx thread]# python bookrank.py
At Mon Jul 15 00:04:39 2019 PDT on Amazon...
- 'Core Python Programming' ranked 925,528
- 'Python Web Development with Django' ranked 816,774
- 'Python Fundamentals' ranked 5,486,078
- 'Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming' ranked 2,458
- 'Learning Python, 5th Edition' ranked 5,080
- 'Introducing Python: Modern Computing in Simple Packages' ranked 56,663
all DONE at: Mon Jul 15 00:05:20 2019
(py3) [root@nginx thread]#
3、多线程执行结果
总共花费20秒,结果是按照线程完成的顺序依次显示的。
(py3) [root@nginx thread]# python bookrank.py
At Mon Jul 15 00:06:19 2019 PDT on Amazon...
- 'Learning Python, 5th Edition' ranked 5,080
- 'Introducing Python: Modern Computing in Simple Packages' ranked 59,953
- 'Python Web Development with Django' ranked 822,261
- 'Core Python Programming' ranked 924,348
- 'Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming' ranked 2,646
- 'Python Fundamentals' ranked 5,486,078
all DONE at: Mon Jul 15 00:06:39 2019
(py3) [root@nginx thread]#
文章评论