<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chetan Mishra on Medium]]></title>
        <description><![CDATA[Stories by Chetan Mishra on Medium]]></description>
        <link>https://medium.com/@chetaniam?source=rss-c4276182b524------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DFoD5xCTScMqRkA_jK_dUQ.png</url>
            <title>Stories by Chetan Mishra on Medium</title>
            <link>https://medium.com/@chetaniam?source=rss-c4276182b524------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:57:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chetaniam/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Optimize python code with generators]]></title>
            <link>https://medium.com/@chetaniam/optimize-python-code-with-generators-aef839996ee4?source=rss-c4276182b524------2</link>
            <guid isPermaLink="false">https://medium.com/p/aef839996ee4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[generator]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Chetan Mishra]]></dc:creator>
            <pubDate>Sun, 21 Apr 2019 10:32:23 GMT</pubDate>
            <atom:updated>2019-04-21T10:32:23.177Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever had to write a method that takes an iterable container (list, set, etc) and have to perform operations over it to return another iterable container as output? If yes, then python generators might be the first optimization tool you should look into.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7bYvEMmBIrRCjwltRUV5Q.jpeg" /></figure><blockquote><strong>What are python generators?<br></strong>Generators are iterators, but you can only iterate over them once. It’s because they do not store all the values in memory, they generate the values on the fly. You use them by iterating over them, either with a ‘for’ loop or by passing them to any function or construct that iterates. Most of the time generators are implemented as functions. However, they do not return a value, they yieldit.</blockquote><p>Let&#39;s see an example of how to use them.<br>Suppose you have a simple function to take a list of numbers and return the cube of all of these numbers like this:</p><pre>def get_cubes(numbers):<br>    cubes = []<br>    for number in numbers:<br>        cubes.append(number * number * number)<br>    return cubes<br><br><br>if __name__ == &#39;__main__&#39;:<br>    cubes = get_cubes([1, 2, 3, 4, 5])<br>    print(type(cubes))<br>    for cube in cubes:<br>        print(cube)</pre><p>This would give you the following output as:</p><pre>&lt;class &#39;list&#39;&gt;<br>1<br>8<br>27<br>64<br>125</pre><p>Notice that the returned object belongs to the list class.<br>You could rewrite the same method using a generator like this</p><pre>def get_cubes(numbers):<br>    for number in numbers:<br>        yield number * number * number<br><br><br>if __name__ == &#39;__main__&#39;:<br>    cubes = get_cubes([1, 2, 3, 4, 5])<br>    print(type(cubes))<br>    for cube in cubes:<br>        print(cube)</pre><p>Now the output is this:</p><pre>&lt;class &#39;generator&#39;&gt;<br>1<br>8<br>27<br>64<br>125</pre><p>This time the returned object is of the generator class.<br>Notice that we did not have to make any changes in the code calling the method here even though the return type is different! That’s because both of these objects areiterable objects.</p><p><strong><em>If the calling code and the result in both cases are the same then what is the advantage of using generators?<br></em></strong>The advantage lies in the fact that generators don’t store all results in memory whereas they generate them on the fly, hence the memory is only used when you ask for the result and not before that.<br>This doesn’t just save us memory but also time.<br>Let’s verify this practically.</p><p>Here is the same program with the added code to calculate the time and memory footprint of the method call.<br>Also, we’ll use range function to get a large list of numbers as input to the get_cubes method so that we get a significant number in time_diff and mem_diff .<br>I’ll be using the built-in time library to calculate runtime and an open-source tool memory_profiler (<em>pip install memory-profiler</em>) to get the memory footprint.</p><p><strong>Scenario 1- Without generators</strong></p><pre>import memory_profiler<br>import time</pre><pre>def get_cubes(numbers):<br>    cubes = []<br>    for number in numbers:<br>        cubes.append(number * number * number)<br>    return cubes<br><br><br>if __name__ == &#39;__main__&#39;:<br><br>    # memory before method call<br>    m1 = memory_profiler.memory_usage()<br>    # start time<br>    t1 = time.clock()<br><br>    cubes = get_cubes(range(10000000))<br><br>    # end time<br>    t2 = time.clock()<br>    # memory after method call<br>    m2 = memory_profiler.memory_usage()<br>    time_diff = t2 - t1<br>    mem_diff = m2[0] - m1[0]<br>    print(f&quot;It took {time_diff} Secs and {mem_diff} Mb to execute this method&quot;)</pre><p>The output is -</p><pre>It took 2.294268 Secs and 408.66015625 Mb to execute this method</pre><p><strong>Scenario 2- Using generators</strong></p><pre>import memory_profiler<br>import time<br><br><br>def get_cubes(numbers):<br>    for number in numbers:<br>        yield number * number * number<br><br><br>if __name__ == &#39;__main__&#39;:<br>    # memory before method call<br>    m1 = memory_profiler.memory_usage()<br>    # start time<br>    t1 = time.clock()<br><br>    cubes = get_cubes(range(10000000))<br>   <br>    # end time<br>    t2 = time.clock()<br>    # memory after method call<br>    m2 = memory_profiler.memory_usage()<br>    time_diff = t2 - t1<br>    mem_diff = m2[0] - m1[0]<br>    print(f&quot;It took {time_diff} Secs and {mem_diff} Mb to execute this method&quot;)</pre><p>The output is -</p><pre>It took 6.1000000000005494e-05 Secs and 0.01953125 Mb to execute this method</pre><p>As you can see, in Scenario-2, no significant memory in taken and also the execution time is insignificant, while in Scenario-1 we needed 2.29 sec of time and huge memory to execute this.<br>Even if you start iterating over the result of the method in case of Scenario-2, there will only be an increase in the execution time whereas the memory usage is going to remain almost the same.</p><p>So if we add code to iterate over the result with a for loop -</p><pre>cubes = get_cubes(range(10000000))<br>for c in cubes:<br>    # do something here</pre><p>The result in <strong>Scenario-1 (without generators) </strong>is this:</p><pre>It took 2.9292 Secs and 477.7421875 Mb to execute this method</pre><p>The result in <strong>Scenario-2 (using generators) </strong>is as such:</p><pre>It took 2.563005 Secs and 0.01953125 Mb to execute this method</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aef839996ee4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A brief guide to priority and nice values in the linux ecosystem]]></title>
            <link>https://medium.com/@chetaniam/a-brief-guide-to-priority-and-nice-values-in-the-linux-ecosystem-fb39e49815e0?source=rss-c4276182b524------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb39e49815e0</guid>
            <category><![CDATA[nice-value]]></category>
            <category><![CDATA[priorities]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[renice]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Chetan Mishra]]></dc:creator>
            <pubDate>Tue, 16 Apr 2019 22:31:02 GMT</pubDate>
            <atom:updated>2019-04-16T22:31:02.744Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*hTM5HojdBzMvn7t6D0y5kg.png" /></figure><p>How does Linux do memory management to execute your processes is a little complicated thing to explain. But luckily all the abstracted details around memory management like memory allocation and context switching b/w processes are very well optimized and developers don’t have to worry about these things while writing high-level code.</p><p>What we should generally take into consideration is the amount of CPU bandwidth that our processes are eligible for, especially in cases of contention with other processes sharing the processing power of the CPU.</p><p>Before we jump into the priority and nice values and how they help us; It is important to have a top-level understanding of how CPUs run multiple processes at the same time.<br>Basically, if a CPU has <strong><em>n </em></strong>cores then it can only execute <strong><em>n </em></strong>processes in parallel.<br>When the number of processes is more than <strong><em>n</em></strong>, the processes are switched between very fast using advanced context-switching mechanisms to provide multitasking. This lets us run multiple processes on a CPU even if it has just 1 core.</p><p><strong>Why worry about the priority of your process?<br></strong>Some processes may be highly CPU-intensive but not as important as others and hence can have a lower priority while others may or may not be highly CPU-intensive but are very important and hence should have higher priority.<br>For example- if there is a process <strong>A</strong>, which detects fraud with input data and there is another process <strong>B</strong>, which makes hourly backups of some data, then the priority(A) &gt; priority(B)!<br>This ensures that if both A and B are running at the same time, A would be allocated more processing bandwidth.</p><p>Now that we have enough context, let’s dive into the specifics.</p><p><strong>Priority value — </strong>The priority value is the process’s actual priority which is used by the Linux kernel to schedule a task.<br>In Linux system priorities are 0 to 139 in which 0 to 99 for real-time and 100 to 139 for users.</p><p><strong>Nice value — </strong>Nice values are user-space values that we can use to control the priority of a process. The nice value range is -20 to +19 where -20 is highest, 0 default and +19 is lowest.</p><p>The relation between nice value and priority is as such -<br>Priority_value = Nice_value + 20</p><p>To see how these work together let us take a process that takes a lot of processing power continuously. I’ll use a shell script <em>(infinite.sh) </em>which has an infinite loop in it to demonstrate how this works.</p><pre>cat &gt; infinite.sh<br>#!/bin/bash<br>for (( ; ; ))<br>do<br> continue<br>done</pre><p>We’ll run this on a single core CPU for easy understanding &amp; use <strong>top command </strong>(a<strong> </strong>program that periodically displays a sorted list of system processes and their details like pid, priority value, nice value, CPU usage, etc.) to monitor processes.<br>The output for top before running infinite.sh:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKAdBSt_cncne1AI3HIiMg.png" /><figcaption>Output of top command before running infinite.sh</figcaption></figure><p>Once we run infinite.sh in the background using sh infinite.sh &amp; we see that this process <em>(PID-28)</em> is taking 100% processing power of the CPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f36RknaJ3WP57OTVooPGhA.png" /></figure><p>If I run two more processes of infinite.sh then all of them <em>(PID-28,30,32) </em>get equal CPU as all have the same priority.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzHaOy_XtCabhU4DBfahig.png" /></figure><p>Now let us give these processes different nice values.<br>There are two ways to do this:<br>1. Start the process with the nice value in the command as <br>nice -n nice_val [command] <br>For us, it could be something like nice -n 10 sh infinite.sh &amp; <br>When we run this we get another process <em>(PID-34)</em> with the priority as <strong>30</strong> (as priority = 20 + nice_value). As it has the least priority, it gets the least amount of CPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32qxhCSC48DvCfh65My4lw.png" /></figure><p>2. Change the nice value of a running process using its PID using renice as renice -n nice_val -p [pid] <br>For us, it could be something like renice -n 5 -p 28 <br>When we run this, the process with<em> PID-28 </em>gets its priority set from 20 to 25 and the CPU is allocated accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsEltnCVPvdhn33wR47P5Q.png" /></figure><p>Note: Only root user can set the nice value from -20 to 19. Other users can only set nice values from 0 to 19.</p><p>You can also use renice to set nice values to all processes by a user using renice -n nice_val -u [user]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb39e49815e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a simple scheduling service with APScheduler]]></title>
            <link>https://medium.com/@chetaniam/writing-a-simple-scheduling-service-with-apscheduler-dfbabc62e24a?source=rss-c4276182b524------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfbabc62e24a</guid>
            <category><![CDATA[python-flask]]></category>
            <category><![CDATA[apscheduler]]></category>
            <category><![CDATA[scheduler]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chetan Mishra]]></dc:creator>
            <pubDate>Thu, 26 Jul 2018 20:06:31 GMT</pubDate>
            <atom:updated>2018-07-26T20:06:31.722Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are looking for a quick but scalable way to get a scheduling service up and running for a task, <a href="https://apscheduler.readthedocs.io/en/latest/userguide.html">APScheduler</a> might just be the trick you are looking for.</p><p>You can start using this scheduler right from the start of the development of your application and scale it as per your product scales.</p><p>A simple flask app to do just this would look something like this</p><pre><strong>from </strong>flask <strong>import </strong>Flask, request<br><strong>from </strong>apscheduler.schedulers.background <strong>import </strong>BackgroundScheduler<br><strong>from </strong>datetime <strong>import </strong>datetime<br>schedule_app = Flask(__name__)<br><br># initialize scheduler with your preferred timezone<br>scheduler = BackgroundScheduler({&#39;apscheduler.timezone&#39;: &#39;Asia/Calcutta&#39;})<br>scheduler.start()<br><br><br><br>@schedule_app.route(&#39;/schedulePrint&#39;, methods=[&#39;POST&#39;])<br><strong>def schedule_to_print</strong>():<br>    data = request.get_json()<br>    #get time to schedule and text to print from the json<br>    time = data.get(&#39;time&#39;)<br>    text = data.get(&#39;text&#39;)<br>    #convert to datetime<br>    date_time = datetime.strptime(str(time), &#39;%Y-%m-%dT%H:%M&#39;)<br>    #schedule the method &#39;printing_something&#39; to run the the given &#39;date_time&#39; with the args &#39;text&#39;<br>    job = scheduler.add_job(printing_something, trigger=&#39;date&#39;, next_run_time=str(date_time),<br>                            args=[text])<br>    <strong>return </strong>&quot;job details: %s&quot; % job<br><br><br><strong>def printing_something</strong>(text):<br>    print(&quot;printing %s at %s&quot; % (text, datetime.now()))</pre><p>If I hit my server at with a curl I get the following response</p><pre>curl -X POST http://127.0.0.1:5000/schedulePrint  -H &#39;content-type: application/json&#39; -d &#39;{&quot;time&quot;:&quot;2018-07-27T01:25&quot;,&quot;text&quot;: &quot;apscheduler&quot;}&#39;</pre><pre>job details: printing_something (trigger: date[2018-07-27 01:24:54 IST], next run at: 2018-07-27 01:25:00 IST</pre><p>And at the scheduled time it printed — <strong>printing apscheduler at 2018–07–27 01:25:00.005645</strong></p><p>Now, if we don’t mention any <em>‘jobstore’</em> for the scheduler then it will be an in-memory store, which means the scheduled jobs will be lost if your application restarts.</p><p>To tackle this problem and scale up, you might want to use a persistent data storage. At this stage, a light sql db would suffice — <a href="https://www.sqlalchemy.org/">sqlalchemy</a>.</p><pre><strong>from </strong>flask <strong>import </strong>Flask, request<br><strong>from </strong>apscheduler.schedulers.background <strong>import </strong>BackgroundScheduler<br><strong>from </strong>datetime <strong>import </strong>datetime<br>schedule_app = Flask(__name__)<br><br># initialize scheduler with your preferred timezone<br>scheduler = BackgroundScheduler({&#39;apscheduler.timezone&#39;: &#39;Asia/Calcutta&#39;})<br># add a custom jobstore to persist jobs across sessions (default is in-memory)<br>scheduler.add_jobstore(&#39;sqlalchemy&#39;, url=&#39;sqlite:////tmp/schedule.db&#39;)<br>scheduler.start()<br><br><br><br>@schedule_app.route(&#39;/schedulePrint&#39;, methods=[&#39;POST&#39;])<br><strong>def schedule_to_print</strong>():<br>    data = request.get_json()<br>    #get time to schedule and text to print from the json<br>    time = data.get(&#39;time&#39;)<br>    text = data.get(&#39;text&#39;)<br>    #convert to datetime<br>    date_time = datetime.strptime(str(time), &#39;%Y-%m-%dT%H:%M&#39;)<br>    #schedule the method &#39;printing_something&#39; to run the the given &#39;date_time&#39; with the args &#39;text&#39;<br>    job = scheduler.add_job(printing_something, trigger=&#39;date&#39;, next_run_time=str(date_time),<br>                            args=[text])<br>    <strong>return </strong>&quot;job details: %s&quot; % job<br><br><br><strong>def printing_something</strong>(text):<br>    print(&quot;printing %s at %s&quot; % (text, datetime.now()))</pre><p>If the product scales further and you move to a more distributed setup, you could just replace the jobstore with a central zookeeper or mongo to scale up.</p><pre>scheduler.add_jobstore(&#39;zookeeper&#39;, path=&lt;path_in_zk_to_store_metadata&gt;, client=KazooClient(hosts=&lt;zookeeper_hosts&gt;))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfbabc62e24a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using scrapy to create a generic and scalable crawling framework]]></title>
            <link>https://medium.com/@chetaniam/using-scrapy-to-create-a-generic-and-scalable-crawling-framework-83d36732181?source=rss-c4276182b524------2</link>
            <guid isPermaLink="false">https://medium.com/p/83d36732181</guid>
            <category><![CDATA[crawling]]></category>
            <category><![CDATA[scrapy]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chetan Mishra]]></dc:creator>
            <pubDate>Mon, 09 Jul 2018 06:14:40 GMT</pubDate>
            <atom:updated>2018-07-26T20:15:31.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJNS0JVl7RsVDTmORGZ6xA.png" /></figure><p>A simple framework which can scale to crawling multiple websites without having to make changes in the code regularly.</p><p><strong>Requisites:<br><em> </em></strong><em>1. </em><a href="https://scrapy.org/"><em>Scrapy</em></a><em> <br></em> <em>2. </em><a href="https://scrapyd.readthedocs.io/en/stable/"><em>Scrapyd</em></a><em><br>3. </em><a href="http://kafka.apache.org/"><em>Kafka</em></a></p><p>We’ll go through the process step-by-step to understand the underlying reasons behind doing things a certain way and build up to the final product.<br>Also, we’ll try to solve the bigger problem (crawling websites regularly) which will finally result into solving other small problems (scraping a single page, extracting links from a page, etc) automatically.</p><p><strong>Logical devision:<br></strong>Let’s think of crawling a website as a three step process -<br>a) <em>URL extraction:</em> First we’ll try to get those pages (links) of a website which have the content we are trying to scrape.<br>b) <em>Content scraping: </em>Then we would use the url found to extract data out of this page.<br>c) <em>Post extraction pipeline: </em>Once we have some data, we would like to do something with it (store it in a db, publish it on a channel, etc)</p><p><strong>URL extraction:<br></strong>Create a spider using scrapy’s built in <a href="https://doc.scrapy.org/en/latest/topics/spiders.html#scrapy-spider">Spider</a> and <a href="https://doc.scrapy.org/en/latest/topics/link-extractors.html">LinkExtractor</a> to extract links. The only thing we’ll do differently here is to take a parameter as <strong><em>root</em> </strong>at runtime<em>,</em> which will be the url of the source page we need to start extracting links from.<br>We also take a depth parameter for cases where we need to extract links for depth &gt; 0 (this will be optional with default 0).<br>Apart from these, we can optionally get values for the <a href="https://doc.scrapy.org/en/latest/topics/link-extractors.html#module-scrapy.linkextractors.lxmlhtml">parameters</a> of LinkExtractor so that we can configure it on runtime.</p><pre><strong>from </strong>scrapy.spiders <strong>import </strong>Spider<br><strong>from </strong>scrapy <strong>import </strong>Request<br><strong>from </strong>scrapy.linkextractors <strong>import </strong>LinkExtractor<br><br><strong>class UrlExtractor</strong>(Spider):<br>    name = &#39;url-extractor&#39;<br>    start_urls = []<br><br>    <strong>def </strong>__init__(self, root=<strong>None</strong>, depth=0, *args, **kwargs):<br>        self.logger.info(&quot;[LE] Source: %s Depth: %s Kwargs: %s&quot;, root, depth, kwargs)<br>        self.source = root<br>        self.options = kwargs<br>        self.depth = depth<br>        UrlExtractor.start_urls.append(root)<br>        UrlExtractor.allowed_domains = [self.options.get(&#39;allow_domains&#39;)]<br>        self.clean_options()<br>        self.le = LinkExtractor(allow=self.options.get(&#39;allow&#39;), deny=self.options.get(&#39;deny&#39;),<br>                                allow_domains=self.options.get(&#39;allow_domains&#39;),<br>                                deny_domains=self.options.get(&#39;deny_domains&#39;),<br>                                restrict_xpaths=self.options.get(&#39;restrict_xpaths&#39;),<br>                                canonicalize=<strong>False</strong>,<br>                                unique=<strong>True</strong>, process_value=<strong>None</strong>, deny_extensions=<strong>None</strong>,<br>                                restrict_css=self.options.get(&#39;restrict_css&#39;),<br>                                strip=<strong>True</strong>)<br>        super(UrlExtractor, self).__init__(*args, **kwargs)<br><br>    <strong>def start_requests</strong>(self, *args, **kwargs):<br>        <strong>yield </strong>Request(&#39;%s&#39; % self.source, callback=self.parse_req)<br><br>    <strong>def parse_req</strong>(self, response):<br>        all_urls = []<br>        <strong>if </strong>int(response.meta[&#39;depth&#39;]) &lt;= int(self.depth):<br>            all_urls = self.get_all_links(response)<br>            <strong>for </strong>url <strong>in </strong>all_urls:<br>                <strong>yield </strong>Request(&#39;%s&#39; % url, callback=self.parse_req)<br>        <strong>if </strong>len(all_urls) &gt; 0:<br>            <strong>for </strong>url <strong>in </strong>all_urls:<br>                <strong>yield </strong>dict(link=url, meta=dict(source=self.source, depth=response.meta[&#39;depth&#39;]))<br><br>    <strong>def get_all_links</strong>(self, response):<br>        links = self.le.extract_links(response)<br>        str_links = []<br>        <strong>for </strong>link <strong>in </strong>links:<br>            str_links.append(link.url)<br>        <strong>return </strong>str_links<br><br>    <strong>def clean_options</strong>(self):<br>        allowed_options = [&#39;allow&#39;, &#39;deny&#39;, &#39;allow_domains&#39;, &#39;deny_domains&#39;, &#39;restrict_xpaths&#39;, &#39;restrict_css&#39;]<br>        <strong>for </strong>key <strong>in </strong>allowed_options:<br>            <strong>if </strong>self.options.get(key, <strong>None</strong>) <strong>is None</strong>:<br>                self.options[key] = []<br>            <strong>else</strong>:<br>                self.options[key] = self.options.get(key).split(&#39;,&#39;)</pre><p>This will allow us to extract links from a website at runtime.<br>Ex: If you needed to extract only the links or articles (ignoring photo stories and photo-galleries) from the <a href="https://indianexpress.com/">IndianExpress</a> website, you could just trigger this spider from your project as</p><pre>scrapy crawl url-extractor -a root=http://indianexpress.com/ -a allow_domains=&quot;indianexpress.com&quot; -a depth=0 -a allow=&quot;/article/&quot;</pre><p><strong>Content Scraping:<br></strong>Now we’ll create a spider which can scrape the content of given url.<br>We want such a scraper where we could pass the config on runtime and get the result scraped in a dictionary of the labels we’d want finally.<br>For this example we’ll scrape data from the page using css <a href="https://doc.scrapy.org/en/latest/topics/selectors.html">selectors</a> (you can use xpath or even keep this runtime configurable).</p><pre><strong>import </strong>json<br><strong>import </strong>re<br><strong>import </strong>scrapy<br><br><br><strong>class Scraper</strong>(scrapy.spiders.Spider):<br>    name = &#39;scraper&#39;<br><br>    <strong>def </strong>__init__(self, page=<strong>None</strong>, config=<strong>None</strong>, mandatory=<strong>None</strong>, *args, **kwargs):<br>        self.page =page<br>        self.config = json.loads(config)<br>        self.mandatory_fields = mandatory.split(&#39;,&#39;)<br>        super(Scraper, self).__init__(*args, **kwargs)<br><br>    <strong>def start_requests</strong>(self):<br>        self.logger.info(&#39;Start url: %s&#39; % self.page)<br>        <strong>yield </strong>scrapy.Request(url=self.page, callback=self.parse)<br><br>    <strong>def parse</strong>(self, response):<br>        item = dict(url=response.url)<br>        # iterate over all keys in config and extract value for each of them<br>        <strong>for </strong>key <strong>in </strong>self.config:<br>            # extract the data for the key from the html response<br>            res = response.css(self.config[key]).extract()<br>            # if the label is any type of url then make sure we have an absolute url instead of a relative one<br>            <strong>if </strong>bool(re.search(&#39;url&#39;, key.lower())):<br>                res = self.get_absolute_url(https://medium.com/response,%20res)<br>            item[key] = &#39; &#39;.join(elem <strong>for </strong>elem <strong>in </strong>res).strip()<br><br>        # ensure that all mandatory fields are present, else discard this scrape<br>        mandatory_fileds_present = <strong>True<br>        for </strong>key <strong>in </strong>self.mandatory_fields:<br>            <strong>if not </strong>item[key]:<br>                mandatory_fileds_present = <strong>False<br><br>        if </strong>mandatory_fileds_present:<br>            <strong>yield </strong>dict(data=item)<br><br>    @staticmethod<br>    <strong>def get_absolute_url</strong>(response, urls):<br>        final_url = []<br>        <strong>for </strong>url <strong>in </strong>urls:<br>            <strong>if not </strong>bool(re.match(&#39;^http&#39;, url)):<br>                final_url.append(response.urljoin(url))<br>            <strong>else</strong>:<br>                final_url.append(url)<br>        <strong>return </strong>final_url</pre><p>Let’s test this on a TOI <a href="https://timesofindia.indiatimes.com/city/delhi/2014-khirki-extn-raid-court-orders-aaps-somnath-bharti-to-stand-trial/articleshow/64810526.cms">article</a>.<br>When we run this by specifying the article link and the config to extract data like this:</p><pre>scrapy crawl scraper -a page=&#39;https://timesofindia.indiatimes.com/city/delhi/2014-khirki-extn-raid-court-orders-aaps-somnath-bharti-to-stand-trial/articleshow/64810526.cms&#39; -a config=&#39;{&quot;title&quot;:&quot;.heading1 arttitle::text&quot;,&quot;tags&quot;:&quot;meta[itemprop=\&quot;keywords\&quot;]::attr(content)&quot;,&quot;publishedTs&quot;:&quot;meta[itemprop=\&quot;datePublished\&quot;]::attr(content)&quot;,&quot;titleImageUrl&quot;:&quot;link[itemprop=\&quot;thumbnailUrl\&quot;]::attr(href)&quot;,&quot;body&quot;:&quot;.Normal::text&quot;,&quot;siteBreadCrumb&quot;:&quot;span[itemprop=\&quot;name\&quot;]::text&quot;}&#39; -a mandatory=&#39;title&#39;</pre><p>We get a dictionary as output like this:</p><pre>{<br>  &quot;title&quot;: &quot;2014 Khirki Extension raid: Court orders AAP\u2019s Somnath Bharti to stand trial&quot;,<br>  &quot;url&quot;: &quot;<a href="https://timesofindia.indiatimes.com/city/delhi/2014-khirki-extn-raid-court-orders-aaps-somnath-bharti-to-stand-trial/articleshow/64810526.cms">https://timesofindia.indiatimes.com/city/delhi/2014-khirki-extn-raid-court-orders-aaps-somnath-bharti-to-stand-trial/articleshow/64810526.cms</a>&quot;,<br>  &quot;titleImageUrl&quot;: &quot;<a href="https://static.toiimg.com/thumb/msid-64810525,width-1070,height-580,imgsize-1103101,resizemode-6,overlay-toi_sw,pt-32,y_pad-40/photo.jpg">https://static.toiimg.com/thumb/msid-64810525,width-1070,height-580,imgsize-1103101,resizemode-6,overlay-toi_sw,pt-32,y_pad-40/photo.jpg</a>&quot;,<br>  &quot;tags&quot;: &quot;Latest News,Live News,2014 Khirki Extension raid,Somnath Bharti,MLA,minister,Malviya Nagar,Khirki Extension,bharti,AAP,AAP\u2019s Somnath Bharti&quot;,<br>  &quot;publishedTs&quot;: &quot;2018-07-01T07:40:47+05:30&quot;,<br>  &quot;siteBreadCrumb&quot;: &quot;News City News Delhi News Politics&quot;,<br>  &quot;body&quot;: &quot;NEW DELHI: In fresh trouble for former Delhi law   and   MLA  , a Delhi court on Saturday asked him to face trial in connection with a \n  \n\n \n The court brushed aside Bharti\u2019s claim of unfair police probe and ordered framing of charges against him and several other accused for the offences ranging from molestation, house trespass, criminal intimidation etc. Since some of these offences fall in the category of crimes against women, these are non-bailable.\n \n While framing charges additional chief metropolitan magistrate Samar Vishal in his order noted that \u201cBy no stretch of imagination it can be assumed that whatever offences are alleged to have been done by Bharti can be said to have been done in the discharge of his official duties. I am unable to understand what official duty prompted him to assault the helpless women of foreign origin at around 1am.\u201d\n \n Apart from  , 16 others have been booked in the case after the Malviya Nagar   allegedly barged into the homes of nine Ugandan nationals in  , along with some followers, on the intervening night of January 15 and 16.\n \n The court ordered framing of charges against Bharti and others under Sections 147/149 (rioting), 354 (molestation), 354C (voyeurism), 342 (wrongful confinement), 506 (criminal intimidation), 143 (unlawful assembly), 509 (outraging a woman&#39;s modesty), 153A (promoting enmity between two groups or religions), 323 (assault), 452 (house trespass), 427 (criminal trespass) and 186 (obstructing public servant in discharge of public functions) of the IPC.\n \n In the order, the magistrate added that there was sufficient evidence that some of these women were beaten and were caused simple hurt punishable under Section 323 of the IPC. \u201cSome of these women have alleged that they were assaulted and their modesty was outraged, they were forced to urinate in front of the mob and therefore the mob has committed an offence under sections 354 and 354C of IPC.\u201d\n \n In his defence, Bharti had claimed he received a string of complaints from residents of the area that a drugs and prostitution ring was being run by the Ugandan nationals. However, investigations by police revealed that no drugs were recovered that night. During the incident, Bharti also had an altercation with the cops on the issue.\n \n In its chargesheet, the police cited around 41 prosecution witnesses, including nine African women, to buttress the charges levelled following investigations into the FIR lodged on January 19, 2014 against \u201cunknown accused\u201d on the court\u2019s direction and booked them for various charges.&quot;<br>}</pre><p><strong>Post extraction pipeline:</strong></p><p>In your pipeline, you can chose to do anything with the extracted information.<br>You could store it in a database, do some post-processing or write it to a kafka topic.<br>You just need to edit the pipelines.py file according to your needs.<br>For further details see <a href="https://doc.scrapy.org/en/latest/topics/item-pipeline.html">link</a>.</p><p><strong>Why scrapyd?</strong></p><p><a href="http://scrapyd.readthedocs.io/en/stable/">Scrapyd</a> enables us to control our spiders using json api.<br>Which basically means that instead of having to trigger a spider as</p><pre>scrapy crawl url-extractor -a root=http://indianexpress.com/ -a allow_domains=&quot;indianexpress.com&quot; -a depth=0 -a allow=&quot;/article/&quot;</pre><p>you could make a http call to an api as</p><pre>curl http://localhost/schedule.json -d project=default -d spider=url-extractor -d root=http://indianexpress.com/ -d allow_domains=&quot;indianexpress.com&quot; -d depth=0 -d allow=&quot;/article/&quot;</pre><p><strong>Bringing it all together:</strong></p><p>Now that you have all your spiders setup, you’ll need an <em>Orchestrator </em>to bring it all together for you.<br>The orchestrator would be a program that simply triggers the url-extraction for a site -&gt; reads the result produced by the extractor (from a kafka topic) -&gt;triggers page-scraper for all these links.</p><p>It could also hold the configs for url-extractor and page-scraper for sites centrally along with a scheduler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*ODF2ycpIiA9xv1bO3oygWQ.jpeg" /></figure><p><strong>Why all the separation?</strong></p><p>Keeping all these elements separately allows you to scale this model indefinitely.<br>You can now have multiple url-extractors and page-scrapers running simultaneously and a single orchestrator should be enough to control an enormous amount of scraping.<br>As all of these individual elements are sharing data through kafka, it makes it an async process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83d36732181" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>