- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest.py
More file actions
Latest commit
71 lines (62 loc) · 2.37 KB
/
Copy pathtest.py
File metadata and controls
71 lines (62 loc) · 2.37 KB
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
65
66
67
68
69
70
71
#!/usr/bin/python3
# coding=utf-8
importlogging
importre
importaiohttp
importasyncio
frombs4importBeautifulSoup
frompymongoimportMongoClient
classDouBanCrawl():
def__init__(self, url):
self.url=url
asyncdeffetch(self, url, headers):
res=awaitaiohttp.request('GET', url)
body=res.read()
return (awaitbody)
definfos_get(self, html, name=None):
soup=BeautifulSoup(html, 'lxml')
scores=soup.select('.rating_num')
scores= [score.textforscoreinscores]
quotes=soup.select('p.quote > span')
quotes= [quote.textforquoteinquotes]
pattern=r"https://movie.douban.com/subject/\w+/"
hrefs=re.findall(pattern, str(html))[::2]
title_list=soup.select('div.pic > a')
try:
titles= [re.findall(r'alt="(.*?)"', str(title))[0]
fortitleintitle_list]
img_links= [re.findall(r'src="(.*?)"', str(src))[0]
forsrcintitle_list]
exceptIndexError:
pass
returnimg_links, titles, scores, quotes, hrefs
asyncdefsave_info(self, page):
url=self.url.format(page)
# print(url)
withawaitsem:
html=awaitself.fetch(url, headers)
img_links, titles, scores, quotes, hrefs=self.infos_get(html)
forinfosinzip(img_links, titles, scores, quotes, hrefs):
info= {'img': infos[0],
'name': infos[1],
'score': infos[2],
'quote': infos[3],
'href': infos[4]
}
count=coll.find({"name": infos[1]}).count()
ifcount==0:
coll.insert(info)
if__name__=='__main__':
url='https://movie.douban.com/top250?start={}&filter='
headers= {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'}
client=MongoClient('localhost', 27017)
db=client.movies
coll=db.coll
douban=DouBanCrawl(url)
pages=range(0, 250, 25)
sem=asyncio.Semaphore(4) # 限制协程并发量
loop=asyncio.get_event_loop()
f=asyncio.wait([douban.save_info(page) forpageinpages])
loop.run_until_complete(f) # %time 为Ipython 自带功能模块
print('Done')