-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcurrent_futures.py
More file actions
55 lines (40 loc) · 1.25 KB
/
Copy pathconcurrent_futures.py
File metadata and controls
55 lines (40 loc) · 1.25 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
import requests
import bs4
import datetime
# from concurrent.futures import ThreadPoolExecutor as PoolExecutor
from concurrent.futures import ProcessPoolExecutor as PoolExecutor
def get_title(url: str) -> str:
import multiprocessing
p = multiprocessing.current_process()
print(f'Process Id: {p.pid}, Process Name: {p.name}')
response = requests.get(url)
response.raise_for_status()
html = response.text
soup = bs4.BeautifulSoup(html, 'html.parser')
tag = soup.select_one('title')
if not tag:
return 'None'
return tag.text.strip()
def main():
t0 = datetime.datetime.now()
urls = [
'https://toplearn.com',
'https://ordookhani.com',
'https://learnby.ir',
'https://barnamenevisan.info',
'https://toplearn.com/c/6140',
'https://divar.ir',
'https://digikala.com'
]
tasks = []
with PoolExecutor() as executor:
for url in urls:
f = executor.submit(get_title, url)
tasks.append(f)
print('Waiting ...', flush=True)
t1 = datetime.datetime.now() - t0
print(f'Tasks finished in {t1.total_seconds():.2f} seconds')
for task in tasks:
print(f'{task.result()}')
if __name__ == '__main__':
main()