- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathqueue_thread.py
More file actions
Latest commit
46 lines (38 loc) · 1.33 KB
/
Copy pathqueue_thread.py
File metadata and controls
46 lines (38 loc) · 1.33 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
importqueue
importthreading
importtime
importrequests
frombs4importBeautifulSoup
urls= [f"https://www.cnblogs.com/#p{page}"forpageinrange(1, 50+1)]
defcraw(url):
r=requests.get(url)
returnr.text
defparse(html):
soup=BeautifulSoup(html, "html.parser")
links=soup.find_all("a", class_="post-item-title")
return [(link['href'], link.get_text()) forlinkinlinks]
defdo_craw(url_queue: queue.Queue, html_queue: queue.Queue):
whileTrue:
url=url_queue.get()
html=craw(url)
html_queue.put(html)
print(threading.current_thread().name, f"craw {url}", f'queue size {url_queue.qsize()}')
defdo_parse(html_queue: queue.Queue, fout):
whileTrue:
html=html_queue.get()
results=parse(html)
forresultinresults:
fout.write(str(result) +'\n')
print(threading.current_thread().name, f"result size {len(results)}", f'queue size {html_queue.qsize()}')
if__name__=="__main__":
url_queue=queue.Queue()
html_queue=queue.Queue()
forurlinurls:
url_queue.put(url)
foridxinrange(3):
t=threading.Thread(target=do_craw, args=(url_queue, html_queue), name=f"craw thread {idx}")
t.start()
fout=open("./spider.txt", "w")
foridxinrange(2):
t=threading.Thread(target=do_parse, args=(html_queue, fout), name=f"parse thread {idx}")
t.start()