Building a Web Crawler to Construct a Dataset of CNBC Articles

For this project I created a web crawler that scraped the technology section of the CNBC website and I used the data to create a pandas dataframe for further analysis

In [ ]:
import scrapy
import pandas as pd
from scrapy.crawler import CrawlerProcess
In [2]:
article_titles = []
dates = []
authors = []
key_points = []
body = []
In [3]:
class CNBC_SPIDER(scrapy.Spider):
    name = "cnbc_spider"
    def start_requests(self):
        url='https://www.cnbc.com/technology/'
        yield scrapy.Request(url = url, callback= self.parse_front_page)
    
    def parse_front_page(self, response):
        title = response.css('div.Card-titleContainer > a > div::text').extract()
        article_titles.extend(title)
        
        urls = response.css('div.Card-titleContainer > a::attr(href)').extract()
        for url in urls:
            yield response.follow(url = url,callback=self.parse_article)
    
    def parse_article(self, response):
        date = response.css('div.ArticleHeader-time > time:nth-child(1)::text').extract()
        dates.append(date)
        
        author = response.css('a.Author-authorName::text').extract()
        authors.append(author)
        
        kp = response.css('div.RenderKeyPoints-list > div > div > ul > li::text').extract()
        key_points.append(kp)
        
        article_body = response.css('div.group > p::text').extract()
        body.append(article_body)
In [4]:
process = CrawlerProcess()
process.crawl(CNBC_SPIDER)
process.start()
2020-05-04 00:47:23 [scrapy.utils.log] INFO: Scrapy 2.0.0 started (bot: scrapybot)
2020-05-04 00:47:23 [scrapy.utils.log] INFO: Versions: lxml 4.4.1.0, libxml2 2.9.9, cssselect 1.1.0, parsel 1.5.2, w3lib 1.21.0, Twisted 19.10.0, Python 3.7.4 (default, Aug 13 2019, 15:17:50) - [Clang 4.0.1 (tags/RELEASE_401/final)], pyOpenSSL 19.0.0 (OpenSSL 1.1.1d  10 Sep 2019), cryptography 2.7, Platform Darwin-19.4.0-x86_64-i386-64bit
2020-05-04 00:47:23 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor
2020-05-04 00:47:23 [scrapy.crawler] INFO: Overridden settings:
{}
2020-05-04 00:47:23 [scrapy.extensions.telnet] INFO: Telnet Password: 19f42b06e080a7d3
2020-05-04 00:47:23 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.memusage.MemoryUsage',
 'scrapy.extensions.logstats.LogStats']
2020-05-04 00:47:24 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2020-05-04 00:47:24 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2020-05-04 00:47:24 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2020-05-04 00:47:24 [scrapy.core.engine] INFO: Spider opened
2020-05-04 00:47:24 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2020-05-04 00:47:24 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2020-05-04 00:47:24 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/technology/> (referer: None)
2020-05-04 00:47:24 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/03/how-to-change-the-background-on-zoom-to-hide-a-messy-room.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:25 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/elon-musk-interrupts-nasa-call-during-discussion-of-his-coronavirus-views.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:25 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/former-nyc-mayor-bloomberg-is-developing-mobile-apps-to-help-new-york-state-trace-coronavirus-cases.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:25 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/microsoft-build-2020-will-focus-even-more-on-developers.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:25 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/comcast-cmcsa-earnings-q1-2020.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:25 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/29/apple-making-it-easier-to-unlock-iphone-with-a-mask-on.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:25 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/zoom-walks-back-claims-it-has-300-million-daily-active-users.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:25 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/29/elon-musk-slams-coronavirus-shelter-in-place-orders-as-fascist.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:25 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/zoom-choice-of-oracle-cloud-logical-after-news-from-microsoft-google.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:26 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/lime-announces-layoffs-as-coronavirus-batters-scooter-startups.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:26 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/xbox-series-x-on-schedule-xbox-games-could-be-delayed-by-coronavirus.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:26 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/apple-ceo-tim-cook-saw-an-uptick-across-the-board-in-late-april.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:26 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/apple-q2-2020-cash-hoard-heres-how-much-apple-has-on-hand.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:26 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/twitter-twtr-earnings-q1-2020.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:26 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/aws-earnings-q1-2020.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:26 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/schiff-asks-tech-firms-to-follow-facebooks-lead-on-misinformation.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:27 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/amazon-amzn-q1-2020-earnings.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:27 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/01/coronavirus-patients-describe-symptoms-that-last-a-month-or-more.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:27 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/01/how-you-see-your-doctor-could-be-forever-changed-by-coronavirus.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:27 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/01/coronavirus-smartphone-shipments-suffer-worst-annual-q1-decline-idc-says.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:27 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/01/restaurant-owners-in-britain-call-on-deliveroo-to-drop-commission-fees.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:27 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/01/coronavirus-uk-government-invited-deepminds-demis-hassabis-to-meeting.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:27 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/01/coronavirus-traders-adapt-to-life-off-the-trading-floor.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:27 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/apple-aapl-earnings-q2-2020.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:28 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/04/30/bill-gates-what-you-need-to-know-about-a-coronavirus-vaccine.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:28 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/01/tesla-tells-furloughed-workers-expect-a-week-or-more-of-unemployment.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:28 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/01/facebook-google-amazon-ad-revenue-in-q1-versus-q2-outlook.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:28 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/03/americans-pay-for-tv-sports-they-dont-receive---dont-expect-a-refund.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:28 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/02/as-amazon-soars-mid-pandemic-affiliates-feel-theyre-left-behind.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:28 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/01/amazon-investors-may-want-to-take-a-seat-heres-what-that-means.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:28 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/01/tesla-ceo-elon-musk-says-stock-price-is-too-high-shares-fall.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:28 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/01/direct-response-advertising-was-a-hero-for-tech-in-q1.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:28 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/01/how-airlines-found-parking-for-thousands-of-planes-amid-coronavirus.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:29 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.cnbc.com/2020/05/01/house-judiciary-committee-asks-amazon-ceo-jeff-bezos-to-testify-over-allegedly-misleading-congress.html> (referer: https://www.cnbc.com/technology/)
2020-05-04 00:47:29 [scrapy.core.engine] INFO: Closing spider (finished)
2020-05-04 00:47:29 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 14046,
 'downloader/request_count': 35,
 'downloader/request_method_count/GET': 35,
 'downloader/response_bytes': 4696892,
 'downloader/response_count': 35,
 'downloader/response_status_count/200': 35,
 'elapsed_time_seconds': 5.369682,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 5, 4, 4, 47, 29, 423301),
 'log_count/DEBUG': 35,
 'log_count/INFO': 10,
 'memusage/max': 122032128,
 'memusage/startup': 122028032,
 'request_depth_max': 1,
 'response_received_count': 35,
 'scheduler/dequeued': 35,
 'scheduler/dequeued/memory': 35,
 'scheduler/enqueued': 35,
 'scheduler/enqueued/memory': 35,
 'start_time': datetime.datetime(2020, 5, 4, 4, 47, 24, 53619)}
2020-05-04 00:47:29 [scrapy.core.engine] INFO: Spider closed (finished)
In [24]:
df = pd.DataFrame({'title': article_titles,'author':authors, 'date':dates,'key_points':key_points,'body':body })
In [25]:
df['author'] = df['author'].apply(lambda x: ', '.join(x))
In [29]:
df['date'] = df['date'].apply(lambda x: ', '.join(x))
In [36]:
df['body'] = df['body'].apply(lambda x: ' '.join(x))
In [37]:
df.head()
Out[37]:
title author date key_points body
0 How to change the background on Zoom so you ca... Todd Haselton Published Sun, May 3 2020, 9:31 AM EDT [Video chat app Zoom lets you change the backg... Most of your meetings and social events are ...
1 Americans are paying for TV sports they're not... Michael Sheetz Published Thu, Apr 30 2020, 3:13 PM EDT [NASA Administrator Jim Bridenstine was asked ... Elon Musk is having issues with conference cal...
2 As Amazon soars during the pandemic, publisher... Noah Higgins-Dunn, William Feuer Published Thu, Apr 30 2020, 12:31 PM EDT [Former New York City Mayor Michael Bloomberg ... Former New York City Mayor Michael Bloomberg i...
3 Tesla tells furloughed workers to expect a wee... Jordan Novet Published Thu, Apr 30 2020, 1:00 PM EDT [Unlike past years, people will only be able t... on Thursday said it will start accepting regi...
4 Airlines have grounded more than 16,000 planes... Jessica Bursztynsky, Sara Salinas Published Thu, Apr 30 2020, 6:30 AM EDT [Comcast posted $2.1 billion in net income for... reported a nearly 40% drop in profit on Thu...