Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
5003CEM/headlines-non-concurrent-TIMEIT.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
39 lines (34 sloc)
1.36 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import newspaper | |
from newspaper import Article | |
import concurrent.futures | |
import urllib.request | |
def get_headlines(): | |
URLs = ['http://www.foxnews.com/', | |
'http://www.cnn.com/', | |
'http://www.derspiegel.de/', | |
'http://www.bbc.co.uk/', | |
'https://theguardian.com',] | |
for url in URLs: | |
result = newspaper.build(url, memoize_articles=False) | |
print('\n''The headlines from %s are' % url, '\n') | |
for i in range(1,6): | |
art = result.articles[i] | |
art.download() | |
art.parse() | |
print(art.title) | |
# We can use a with statement to ensure threads are cleaned up promptly | |
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: | |
# Start the load operations and mark each future with its URL | |
future_to_url = {executor.submit(url, 60): url for url in URLs} | |
for future in concurrent.futures.as_completed(future_to_url): | |
url = future_to_url[future] | |
try: | |
data = future.result() | |
except Exception as exc: | |
print('%r generated an exception: %s' % (url, exc)) | |
else: | |
print('%r page is %d bytes' % (url, len(data))) | |
if __name__ == '__main__': | |
import timeit | |
elapsed_time = timeit.timeit("get_headlines()", setup="from __main__ import get_headlines", number=2)/2 | |
print(elapsed_time) |