<?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 Irfan Ahmad on Medium]]></title>
        <description><![CDATA[Stories by Irfan Ahmad on Medium]]></description>
        <link>https://medium.com/@irfan-ahmad?source=rss-37c2d2b16101------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*j8y8mDTSY8tMZUZB</url>
            <title>Stories by Irfan Ahmad on Medium</title>
            <link>https://medium.com/@irfan-ahmad?source=rss-37c2d2b16101------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:14:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@irfan-ahmad/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[Dynamic Web Scraping with Selenium Part- VI- Instagram]]></title>
            <link>https://medium.com/geekculture/dynamic-web-scraping-with-selenium-part-vi-instagram-2e326de54266?source=rss-37c2d2b16101------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e326de54266</guid>
            <category><![CDATA[selenium-test-automation]]></category>
            <category><![CDATA[python-selenium]]></category>
            <category><![CDATA[instagram-dm-with-python]]></category>
            <category><![CDATA[python-instagram]]></category>
            <category><![CDATA[dynamic-web-scraping]]></category>
            <dc:creator><![CDATA[Irfan Ahmad]]></dc:creator>
            <pubDate>Thu, 06 Jul 2023 08:29:52 GMT</pubDate>
            <atom:updated>2023-07-06T08:29:52.596Z</atom:updated>
            <content:encoded><![CDATA[<p>This time I was messing with Instagram and the task was to send DMs to a select users. Everything was very easy. The only challenge I faced was to select the user for DM. Let me show what it was.</p><figure><img alt="An image showing Instagram user selection source code behavior" src="https://cdn-images-1.medium.com/max/1024/1*kOcJpA76SM5qdPw0qANFXA.jpeg" /><figcaption>image showing Instagram user selection</figcaption></figure><p>When we click on the ‘send message’ button a dialogue box appears. In the input we have to write the username of 1 or more persons and then select the user from the list shown below the input.</p><p>In our case we have exact usernames. So, we can deduce that the first user shown in the list, highlighted as ‘2’, is the user which is our target for DM. So, we inspect this element and find that it’s a ‘div’ element with ‘role=button’. This has been highlighted as ‘3’ in the image.</p><p>We setup the selenium script to find this element in the dialogue box and click this element whose role is button and text is same as the username. What happened is that the script did click the element and proceeded but actually the action was not performed on the screen. I mean the element was clicked successfully but nothing happened in action.</p><p>After careful observations I found out that actually this element was not the one which gets the click event. Highlighted as ‘4’ is the last ‘div’ element inside our target element. This element was being triggered whenever the main user element was hovered or clicked.</p><p>So, how did I solve this problem?</p><p>I setup the script to move to the main element, highlighted as ‘3’ and then click the ‘4’ element rather than clicking the ‘3’ element. And, it worked.</p><pre>user_main_element = dialogue_element.find_elements(By.XPATH, &quot;//div[@role=&#39;button&#39;]&quot;)[0]<br>ActionChains(self.driver).move_to_element(user_main_element).perform()<br>time.sleep(5)<br>inner_btn = self.driver.find_element(By.XPATH, &quot;/html/body/div[2]/div/div/div[3]/div/div/div[1]/div/div[2]/div/div/div/div/div/div/div[3]/div/div/div[1]/div[2]&quot;)<br>ActionChains(self.driver).click(inner_btn).perform()</pre><p>A very important point in each profession is that we learn by experience. Without experiment we can not learn a lot and can not get better and better result. And, learning from the others’ experience is also a genius.</p><p>So, don’t forget to subscribe so that you may learn from my experience and apply on your experience to nurture great ideas. Also, don’t forget to give a clap of appreciation so that I may continue sharing my experience.</p><p>See you next time,</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e326de54266" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/dynamic-web-scraping-with-selenium-part-vi-instagram-2e326de54266">Dynamic Web Scraping with Selenium Part- VI- Instagram</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Dynamic Web Scraping]]></title>
            <link>https://medium.com/geekculture/dynamic-web-scrapinmastering-dynamic-web-scraping-ad8f5b3f7390?source=rss-37c2d2b16101------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad8f5b3f7390</guid>
            <category><![CDATA[dynamic-web-scraping]]></category>
            <category><![CDATA[web-scraping-with-python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-web-scraping]]></category>
            <category><![CDATA[selenium-webdriver]]></category>
            <dc:creator><![CDATA[Irfan Ahmad]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 09:25:10 GMT</pubDate>
            <atom:updated>2023-03-29T11:19:55.310Z</atom:updated>
            <content:encoded><![CDATA[<h4>Techniques and Strategies for Success, The Next Chapter</h4><p>Developers are constantly overcoming challenges related to JavaScript in websites. As the world of web scraping evolves, website creators are also developing new strategies to counter scrapers. This continuous tug of war has led to various advancements in dynamic web scraping techniques. In this article, we’ll explore how to extract data from modern websites and overcome the challenges that dynamic web scraping presents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*8Fk6wAjcrKZEQeqZ69PZNA.jpeg" /><figcaption><a href="https://www.ardorsys.com/blog/wp-content/uploads/2020/06/dynamic-web-scraping-python.jpg">dynamic-web-scraping-python.jpg</a></figcaption></figure><h3>Getting a Grip on Dynamic Websites</h3><p>Understanding the workings of dynamic websites is crucial. These sites employ JavaScript and AJAX to load content asynchronously, which means the content is fetched and displayed without a complete page reload. This approach complicates traditional web scraping methods, as the content may not be readily available when the page source is fetched.</p><h3>Picking the Right Weapons: Tools and Libraries</h3><p>Selecting the right tools and libraries is key to success in dynamic web scraping. Some popular choices include:</p><ul><li>Selenium: A powerful web automation and testing framework that controls browsers and interacts with dynamic web pages.</li><li>Puppeteer: A Node.js library that provides a high-level API to control headless Chrome or Chromium browsers.</li><li>Beautiful Soup: A Python library used for web scraping purposes to extract data from HTML and XML files. Combine it with Selenium to handle dynamic content.</li></ul><h3>Inspecting and Navigating the DOM: A Vital Skill</h3><p>The Document Object Model (DOM) is a programming interface for HTML and XML documents. Learning how to inspect and navigate the DOM is essential for identifying the data you want to extract from a dynamic website. Use browser developer tools, such as Chrome DevTools, to inspect the DOM, identify the appropriate elements, and determine the best way to access the data.</p><h3>Becoming an Expert in XPath and CSS Selectors</h3><p>XPath and CSS selectors are crucial for locating and targeting specific elements within the DOM. Both methods offer powerful and flexible ways to target elements. By mastering their use, you’ll significantly improve your web scraping capabilities.</p><h3>Managing AJAX Requests and Awaiting Elements to Load</h3><p>Dynamic websites often load data asynchronously through AJAX requests. To ensure you can access this data, learn to identify and intercept AJAX requests using browser developer tools. Additionally, when using tools like Selenium or Puppeteer, make sure your code waits for elements to load before attempting to extract data.</p><h3>Controlling Browser Sessions and Cookies</h3><p>Some websites require user authentication or track session information through cookies. To effectively scrape these sites, learn to manage browser sessions and cookies using your chosen web scraping library. This will enable you to maintain the necessary state across multiple requests and pages.</p><h3>Practicing Respect and Compliance</h3><p>Web scraping can put significant stress on a server and may violate a website’s terms of service. To maintain ethical practices, adhere to the site’s robots.txt rules, limit your request rate, and always identify your scraper with a custom user agent. Additionally, be aware of any legal or privacy implications when collecting data.</p><h3>In Conclusion</h3><p>Mastering dynamic web scraping involves understanding the fundamentals of dynamic websites, choosing the right tools, and learning essential techniques for extracting data. By following the strategies outlined in this article, you’ll be well on your way to unlocking the full potential of data extraction from modern, dynamic websites. Keep refining your skills and exploring new methods to stay ahead of the curve in the ever-evolving world of web scraping.</p><blockquote>We’ll be diving deeper into dynamic web scraping strategies in future articles. To stay in the loop and help fuel my motivation, please give this article a like, follow my page, and subscribe to my newsletter. Your support keeps me inspired!</blockquote><p><a href="https://irfan-ahmad.medium.com/">Here</a> you’ll find article related to dynamic web scraping with selenium.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad8f5b3f7390" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/dynamic-web-scrapinmastering-dynamic-web-scraping-ad8f5b3f7390">Mastering Dynamic Web Scraping</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping Ethics and Legality]]></title>
            <link>https://medium.com/geekculture/web-scraping-ethics-and-legality-cabd8695866a?source=rss-37c2d2b16101------2</link>
            <guid isPermaLink="false">https://medium.com/p/cabd8695866a</guid>
            <category><![CDATA[ethics-in-tech]]></category>
            <category><![CDATA[selenium-webdriver]]></category>
            <category><![CDATA[selenium-web-scraping]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[ethics-in-web-scraping]]></category>
            <dc:creator><![CDATA[Irfan Ahmad]]></dc:creator>
            <pubDate>Fri, 17 Mar 2023 17:26:11 GMT</pubDate>
            <atom:updated>2023-03-19T10:19:58.756Z</atom:updated>
            <content:encoded><![CDATA[<p>Web scraping is a technique of extracting data from websites using automated tools or scripts. Web scraping can be used for various purposes, such as price comparison, market research, data analysis, content aggregation, etc. You can learn more about it from <a href="https://medium.com/geekculture/web-scraping-why-484f4a00d9d2">here</a>.<br>However, web scraping also raises some ethical and legal questions that need to be addressed by web scrapers and website owners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-lQB4GW01EZ__pqC" /><figcaption>Photo by <a href="https://unsplash.com/it/@tingeyinjurylawfirm?utm_source=medium&amp;utm_medium=referral">Tingey Injury Law Firm</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is ethical web scraping?</h3><p>Ethical web scraping is a term that refers to web scraping practices that respect the rights and interests of both the data providers (website owners) and the data consumers (web scrapers). Ethical web scraping follows some basic principles, such as:</p><ul><li>Do not scrape data that is not publicly available or that requires authentication or authorization.</li><li>Do not scrape data that contains personally identifiable information (PII) or sensitive information without consent or proper anonymization.</li><li>Do not scrape data that infringes on intellectual property rights or violates terms of service (TOS) of the website.</li><li>Do not scrape data at a high frequency or volume that may harm the website’s performance or functionality.</li><li>Do not use scraped data for malicious or illegal purposes.</li></ul><p>Ethical web scraping benefits both parties by ensuring fair use of data, protecting privacy and security, avoiding legal disputes, and maintaining good relationships.</p><h3>What are the legal issues of web scraping?</h3><p>Web scraping is not explicitly regulated by any specific law in most countries. However, there are some existing laws and regulations that may apply to web scraping activities depending on the context and jurisdiction. Some of these laws and regulations include:</p><ul><li>Data protection laws: These laws aim to protect the privacy and security of personal data collected, processed, stored, or transferred by individuals or organizations. Examples of such laws are GDPR in EU and CCPA in California. Web scrapers should comply with these laws when scraping personal data or when operating in regions where these laws apply.</li><li>Copyright laws: These laws protect the original expression of ideas in various forms of media from unauthorized copying or distribution. Web scrapers should respect the copyright ownership of the content they scrape and avoid infringing on it.</li><li>Computer fraud and abuse laws: These laws prohibit unauthorized access to computer systems or networks for obtaining information or causing damage. Web scrapers should not bypass any security measures or authentication mechanisms on websites they scrape.</li><li>Contract laws: These laws govern the agreements between parties that create legal obligations. Web scrapers should abide by the terms of service (TOS) or other contracts they agree to when accessing websites they scrape.</li></ul><p>Web scrapers should be aware of these legal issues and consult with legal experts before engaging in web scraping activities that may involve risks.</p><h3>How to practice ethical and legal web scraping?</h3><p>To practice ethical and legal web scraping, web scrapers should follow some best practices, such as:</p><ul><li>Use proxy servers or VPN services to rotate IP addresses and avoid being blocked by websites.</li><li>Use user-agent rotation to change the identity of the browser and operating system from which the request is executed.</li><li>Follow robots.txt and terms of service (TOS) of the websites and respect their crawling rules and restrictions.</li><li>Minimize the load on the websites by limiting the number of concurrent requests and scraping during off-peak hours.</li><li>Change the crawling pattern to avoid being detected by anti-bot mechanisms that analyze request frequency, interval, repetition, etc.</li><li>Handle client-side rendering by using tools that can execute JavaScript or AJAX calls and render dynamic content.</li><li>Handle CAPTCHAs by using tools that can solve them automatically or manually.</li><li>Verify if you need geotargeting before running your scraper to access location-specific data.</li></ul><h3>How does a legal consultant look at it?</h3><blockquote>Web scraping is a complex issue that requires careful consideration of ethical and legal implications. It’s important to respect website owners’ terms of service and applicable laws when accessing and using their data.</blockquote><blockquote>(<a href="http://facebook.com/att.najam">Najam ul Hassan, Legal Consultant</a>)</blockquote><h3>Conclusion</h3><p>Web scraping is a powerful technique that can provide valuable data for various purposes. However, web scraping also involves ethical and legal challenges that need to be considered by web scrapers and website owners. By following some best practices and guidelines, web scrapers can ensure ethical and legal web scraping that respects both parties’ rights and interests.</p><h3>References</h3><p><a href="https://www.scraperapi.com/blog/web-scraping-best-practices/">1: Web Scraping Guide: Best Practices and Guidelines | Pluralsight</a> <br><a href="https://prowebscraper.com/blog/web-scraping-best-practices-you-should-follow/">2: Web Scraping Best Practices: ScraperAPI’s Cheat Sheet </a><br><a href="https://research.aimultiple.com/web-scraping/">3: 12 Web Scraping Best Practices You Should Follow in 2021 <br>4: Roadmap to Web Scraping: Use Cases, Methods &amp; Tools in 2023 — AIMultiple</a></p><p><em>Thank you for reading this article on web scraping ethics and legality. I hope you found it useful and informative. If you did, please consider giving it a clap, following me, and subscribing to my email list. This way, you can show your support for my work and stay updated on my future articles.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cabd8695866a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/web-scraping-ethics-and-legality-cabd8695866a">Web Scraping Ethics and Legality</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Web Scraping — 7: Using Proxies with Selenium]]></title>
            <link>https://medium.com/geekculture/dynamic-web-scraping-7-using-proxies-with-selenium-e23e7b8ca888?source=rss-37c2d2b16101------2</link>
            <guid isPermaLink="false">https://medium.com/p/e23e7b8ca888</guid>
            <category><![CDATA[proxy-with-selenium]]></category>
            <category><![CDATA[dynamic-web-scraping]]></category>
            <category><![CDATA[web-scraping-with-python]]></category>
            <category><![CDATA[selenium-webdriver]]></category>
            <category><![CDATA[using-proxies]]></category>
            <dc:creator><![CDATA[Irfan Ahmad]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 07:24:03 GMT</pubDate>
            <atom:updated>2023-03-13T07:30:00.029Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dynamic Web Scraping — 7: Using Proxies with Selenium</h3><p>In my <a href="https://medium.com/geekculture/dynamic-web-scraping-6-using-proxies-f18f17bd3779">previous</a> article, I explained the basics of using proxies, including their definition and purpose, and provided a simple demonstration of their usage. This article aims to offer a straightforward demonstration of how to effectively use proxies with Selenium for dynamic web scraping.</p><p>Let’s jump right into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wM7et8Ifo9Rsl30H" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my previous article, I illustrated how to scrape proxies from a website and verify their functionality, ultimately storing the functional proxies in a ‘selected_proxies.csv’ file. I continued this process by regularly updating the proxy list on my GitHub repository to ensure its relevancy. In this article, we will utilize the updated proxy list to randomly select proxies with Selenium and confirm their efficacy by checking the current IP via the ‘whatismyip’ website. This will serve as a useful validation tool to ensure our proxies are functioning as intended.</p><p>This ‘selenium_proxy_test.py’ file is also included in the <a href="https://github.com/Irfan-Ahmad-byte/web_scraping">github repo</a>. The code is divided into three functions. Following is their description.</p><p>main():<br>This function reads the proxies from the selected proxies and then a function ‘get_working_ip’ to get the current IP from the whatismyip website.</p><p>get_working_ip(proxies):<br>This function takes in a list of proxies. From the list it randomly selects a proxy and passes that IP to ‘test_ip’ function.</p><p>test_ip(ip_address):<br>This function takes the IP address and opens a browser using selenium with the current IP address. Then it opens the ‘whatismyip.com’ and gets the current ipv4 address. This repeats the process 4 times.</p><p>I have used Remote WebDriver for this purpose and here is the code which implements a proxy with selenium.</p><pre>options = webdriver.ChromeOptions()<br>proxy = f&quot;{ip_address}&quot;<br>options.add_argument(f&quot;--proxy-server={proxy}&quot;)<br>driver = webdriver.Remote(command_executor=&#39;http://localhost:4444&#39;, options=options)<br>driver.get(&#39;https://www.whatismyip.com/&#39;)<br>time.sleep(5)<br>ip = driver.find_element(By.ID, &quot;ipv4&quot;).text</pre><p>The complete code can be found my my <a href="https://github.com/Irfan-Ahmad-byte/web_scraping">github repo</a>.</p><p>*** Don’t forget to clap for my efforts and follow for future updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e23e7b8ca888" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/dynamic-web-scraping-7-using-proxies-with-selenium-e23e7b8ca888">Dynamic Web Scraping — 7: Using Proxies with Selenium</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Web Scraping — 6: Using Proxies]]></title>
            <link>https://medium.com/geekculture/dynamic-web-scraping-6-using-proxies-f18f17bd3779?source=rss-37c2d2b16101------2</link>
            <guid isPermaLink="false">https://medium.com/p/f18f17bd3779</guid>
            <category><![CDATA[proxies-for-web-scraping]]></category>
            <category><![CDATA[free-proxy]]></category>
            <category><![CDATA[web-scraping-with-python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[dynamic-web-scraping]]></category>
            <dc:creator><![CDATA[Irfan Ahmad]]></dc:creator>
            <pubDate>Sun, 05 Mar 2023 10:46:27 GMT</pubDate>
            <atom:updated>2023-03-06T07:15:05.582Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dynamic Web Scraping — 6: Using Proxies</h3><p>I have written five articles about dynamic web scraping using Selenium, which can be found <a href="https://irfan-ahmad.medium.com/">here</a>. However, before we continue exploring this topic further, it’s important to understand an essential aspect of web scraping: proxies.</p><p>In this article, we’ll cover the following topics:</p><ol><li>Why it’s necessary to understand proxies in web scraping</li><li>What are proxies?</li><li>The importance of proxies in web scraping</li><li>How to obtain proxies</li><li>How to use proxies in web scraping</li></ol><p>In this article, we will explore how to scrape free proxies from the “free-proxy-list”, conduct a demonstration of testing them, and store the working proxies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ElysO74nUFUt7bo7" /><figcaption>Photo by <a href="https://unsplash.com/@nate_dumlao?utm_source=medium&amp;utm_medium=referral">Nathan Dumlao</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Why to understand proxies</h4><p>As web scrapers, our scripts can be perceived as intruders by websites. When a website detects an abnormal number of visits from a single IP address, it becomes suspicious and may block the IP to protect its privacy and properties. This can lead to the scraper being unable to access the website, resulting in incomplete or inaccurate data.</p><p>This is where proxies come into play. Proxies allow a scraper to make requests to a website from multiple IP addresses, which can help prevent website blocking and improve the scraper’s anonymity. Therefore, having a good understanding of proxies and their usage is essential for successful web scraping.</p><blockquote>Although not all websites have this mechanism, as web scrapers, we may face problems with getting blocked.</blockquote><p>So,</p><h4>What are proxies?</h4><p>Proxies are intermediary servers that act as a gateway between a user and the internet. When a user sends a request to a website, the request is first sent to the proxy server, which then forwards the request to the website. The website sees the request as coming from the proxy server rather than the user’s IP address. This can be useful for web scraping because it allows a scraper to make requests to a website without revealing its own IP address.</p><h4>The importance of proxies in web scraping</h4><p>Proxies play a crucial role in web scraping. Web scraping involves sending a large number of requests to a website in a short amount of time, which can trigger website security mechanisms such as IP blocking. When a website blocks the IP address of a scraper, the scraper is unable to access the website and collect the data it needs.</p><p>Proxies can help prevent IP blocking by allowing scrapers to make requests to a website from multiple IP addresses. By rotating through a list of proxies, a scraper can make a high volume of requests without triggering IP blocking. Proxies can also improve a scraper’s anonymity, making it more difficult for websites to track the scraper’s activity.</p><blockquote>But, there are ways we can prevent IP blocking while web scraping. To learn more about these techniques, make sure to hit the ‘Follow’ button so that you don’t miss any of our future articles.</blockquote><p>Furthermore, some websites restrict access based on geographic location. By using proxies located in different regions, a scraper can bypass these restrictions and access the website from anywhere in the world.</p><p>In summary, proxies are essential for successful web scraping. They help prevent IP blocking, improve anonymity, and allow access to restricted websites. It is important for web scrapers to have a good understanding of proxies and their usage in order to avoid being detected and blocked by websites.</p><h4>How to obtain proxies</h4><p>There are various types of proxies that can be found on the internet. To obtain them, one can simply search for “free proxies”. After saving the available proxies, it is important to test them for functionality and select the ones that work best.</p><p>Let’s explore how to scrape free proxies from the “free-proxy-list”, conduct a demonstration of testing them, and store the working proxies.</p><ul><li>** I have created a repository on my <a href="https://github.com/Irfan-Ahmad-byte/web_scraping">github</a>. Where I’ll be sharing my web scraping scripts.</li></ul><h4>How to use proxies in web scraping</h4><p>Start by obtaining proxies from a website.</p><pre>import csv<br>import re<br>import requests<br><br><br>def extract_proxies(url, filename):<br>    &quot;&quot;&quot;<br>    Extracts proxy IP addresses and ports from a given URL and writes them to a CSV file.<br><br>    Args:<br>        url (str): The URL to scrape for proxies.<br>        filename (str): The name of the CSV file to write the proxies to.<br>    &quot;&quot;&quot;<br>    # Send a GET request to the URL<br>    response = requests.get(url)<br><br>    # Extract the proxies using a regular expression<br>    proxies = re.findall(r&#39;\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+&#39;, response.text)<br><br>    # Write the proxies to a CSV file<br>    with open(filename, &#39;w&#39;, newline=&#39;&#39;) as csvfile:<br>        writer = csv.writer(csvfile)<br>        for proxy in proxies:<br>            writer.writerow([proxy])<br><br><br>extract_proxies(&#39;https://free-proxy-list.net/&#39;, &#39;proxies.csv&#39;)</pre><p>The above function scrapes all available free proxies from the ‘free-proxy-list’ proxy provider and saves them in a CSV file named ‘proxies.csv’. The next step is to test these proxies and retain only the ones that work properly.</p><p>In addition to testing the proxies, this demo also showcases how to use proxies with the ‘requests’ library. You can find the demonstration on my <a href="https://github.com/Irfan-Ahmad-byte/web_scraping">Github</a> page. Don’t forget to give this article a clap and star <a href="https://github.com/Irfan-Ahmad-byte/web_scraping">my repository</a> to stay updated on future updates.</p><p>Wishing you the best on your learning journey! ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f18f17bd3779" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/dynamic-web-scraping-6-using-proxies-f18f17bd3779">Dynamic Web Scraping — 6: Using Proxies</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping — Why?]]></title>
            <link>https://medium.com/geekculture/web-scraping-why-484f4a00d9d2?source=rss-37c2d2b16101------2</link>
            <guid isPermaLink="false">https://medium.com/p/484f4a00d9d2</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[web-scraping-tools]]></category>
            <category><![CDATA[web-scraping-introduction]]></category>
            <category><![CDATA[selenium-test-automation]]></category>
            <dc:creator><![CDATA[Irfan Ahmad]]></dc:creator>
            <pubDate>Fri, 03 Mar 2023 06:47:25 GMT</pubDate>
            <atom:updated>2023-03-17T05:28:58.836Z</atom:updated>
            <content:encoded><![CDATA[<h3>Web Scraping — Why?</h3><h4>The Power of Data: Why Web Scraping Matters</h4><p>In simple words, web scraping is a technique that is used to extract data from websites. But, is this all? <br>Don’t you ever wonder <br>1. Why is it even done? <br>2. Why some businesses invest in this?<br>3. How profitable can it be?</p><p>In this article we are going to learn about all this. Yeah, I know I was writing about dynamic web scraping and have not yet written a lot about it. But, I thought if people read about web scraping and like it, they should know some basics about it like its reality, its importance, and how businesses profit from web scraping?</p><p>By the end of this article, you’ll have a better understanding of why web scraping is an essential tool for businesses and researchers, and how it can help you achieve your data-related goals. So, let’s dive in!</p><ul><li>** I’ll make sure that lengthy topics be covered in separate article for you to be at easy and stay organized in your life!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XNAM2s7qKmgmLcH7" /><figcaption>Photo by <a href="https://unsplash.com/es/@kmuza?utm_source=medium&amp;utm_medium=referral">Carlos Muza</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>So, what is this, the Web Scraping?</h4><p>Web scraping is the process of extracting data from websites automatically using software tools or, some times, just simple script 🤔. Well, we all know that. By using web scraping tools, it’s possible to collect data from multiple sources quickly and efficiently, which can provide valuable insights for a range of applications. If you have some introduction with Scrapy then you must be aware that multiple pages can be scraped easily. No no, I’m not branding here, just telling.</p><p>Web scraping can include anything from product information and pricing to customer reviews and social media mentions. The extracted data can then be saved to a file or database, where it can be analyzed and used for a range of purposes.</p><p>I think, it’s enough to clear what web scraping is 🙃.</p><h4>The Benefits of Web Scraping for Businesses</h4><p>It’s time to get serious.</p><ul><li><strong>Automated data collection:</strong> Web scraping allows businesses to automate the process of collecting data from multiple sources, saving time and reducing the risk of errors that can occur with manual data entry.</li><li><strong>Cost savings:</strong> With web scraping, businesses can gather data without the need for expensive third-party services or custom-built solutions, which can be costly and time-consuming to develop.</li><li><strong>Competitive insights:</strong> By collecting data on their competitors, businesses can gain valuable insights into their strategies, pricing, and market positioning. This can help businesses identify areas where they can improve and develop more effective marketing strategies.</li><li><strong>Customer insights:</strong> Web scraping can provide businesses with detailed information on their customers’ behavior, preferences, and needs. By analyzing this data, businesses can develop more effective marketing campaigns and better understand how to meet their customers’ needs.</li><li><strong>Industry trends:</strong> By monitoring industry news and trends through web scraping, businesses can stay up-to-date on the latest developments and adjust their strategies accordingly. This can help businesses stay ahead of their competitors and identify new opportunities for growth.</li><li><strong>Data-driven decision-making:</strong> By gathering and analyzing data through web scraping, businesses can make more informed, data-driven decisions. This can help them optimize their operations, identify new opportunities for growth, and improve their overall performance.</li></ul><p>Hope this was digestible. Let me know with your comments 😉.</p><h4>How Web Scraping Saves Time and Money</h4><p>It’s just that simple. Web scraping is done with automated software or script. So, no hiring for data collection agents, no hiring for data entry operators, no need to pay them for their days of work. Businesses hire developers and they less number of developers do the work of greater number of data collectors. The same task is done in fewer days or hours or, may be, minutes.</p><h4>Is it Legal 🤔?</h4><p>To be honest, it’s not always legal. Let me be brief on it.</p><p>Some websites do not allow scraping their data at all and we observe this restriction when we face CAPTCHA. So, when we try to scrap them 🤫. Though they display some of their data publicly, they do not allow scraping. Websites have a ‘robots.txt’ file enlisting the access permissions for bots or script.</p><p>I’ll write about this in detail. <strong>To keep yourself aware of everything, you’ll have to stay in touch with me. So, kindly consider to “Follow” me</strong> 😎.</p><blockquote>We’ll talk about “Web Scraping Ethics and Legality” and “Web Scraping Tools and Techniques” in their own articles.</blockquote><h4>Real-World Applications of Web Scraping</h4><p>Web scraping has become an essential tool for businesses and individuals alike, allowing them to collect valuable data from the web quickly and efficiently. But what are some real-world applications of web scraping? Let’s take a look.</p><ol><li><strong>E-commerce and price monitoring:</strong> One of the most common applications of web scraping is in the e-commerce industry, where businesses use it to monitor prices and product information from their competitors. By collecting this data, businesses can adjust their pricing strategies and stay ahead of the competition.</li><li><strong>Market research:</strong> Web scraping can be used to collect data on consumer trends, industry news, and other market research information. This data can be analyzed to identify new opportunities and make informed business decisions.</li><li><strong>Lead generation:</strong> Businesses can use web scraping to collect contact information from potential customers, including email addresses and phone numbers. This can help businesses generate leads for their sales teams and grow their customer base.</li><li><strong>Social media monitoring:</strong> Web scraping can be used to monitor social media platforms for mentions of a brand or product. This can help businesses identify customer sentiment, monitor their reputation, and stay ahead of potential PR crises.</li><li><strong>Job listings and recruitment:</strong> Web scraping can be used to collect job listings from various websites, making it easier for recruiters to find and reach out to potential candidates. It can also be used to collect information on competitors’ job postings and hiring strategies.</li><li><strong>Scientific research:</strong> Web scraping can be used in scientific research to collect data on various topics, including weather patterns, stock market trends, and medical research. This data can be analyzed to identify patterns and make informed decisions.</li></ol><p>Overall, web scraping has numerous real-world applications across various industries, making it a valuable tool for businesses and individuals alike. By using web scraping, businesses can save time and resources while gaining valuable insights into their industry and customers.</p><p>Wow, ChatGPT is awesome at writing 😁, I used it only under this heading.</p><h4>Web Scraping Best Practices 😑</h4><p>Web scraping can be a powerful tool for collecting data, but it’s important to follow best practices to ensure that you’re doing it legally, ethically, and effectively. Here are some best practices to keep in mind when conducting web scraping:</p><ol><li><strong>Respect the website’s terms of service:</strong> Before scraping a website, make sure you read and understand their terms of service. Some websites explicitly prohibit scraping or require permission before doing so.</li><li><strong>Use proper attribution:</strong> If you’re using scraped data in a public-facing project, make sure to properly attribute the data to its source. This can include providing a link back to the original website or citing the source in a footnote.</li><li><strong>Avoid excessive scraping:</strong> Don’t scrape a website more frequently than necessary, as this can strain the website’s resources and potentially lead to a denial of service attack. Be respectful of the website’s bandwidth and processing power.</li><li><strong>Use ethical scraping techniques:</strong> Avoid scraping private or personal data, and don’t scrape websites that are protected by authentication or security measures. Stick to public-facing data that is freely available to all users.</li><li><strong>Be mindful of copyright and intellectual property laws:</strong> Be careful not to scrape content that is copyrighted or protected by intellectual property laws, such as images or text. Respect the creator’s rights and only use content that is available under a permissive license.</li></ol><p>By following these best practices, you can ensure that your web scraping efforts are legal, ethical, and effective. Always remember to approach web scraping with respect for the websites and data sources you are using, and to use the data you collect in a responsible and transparent way.</p><p>Let’s talk about interesting things.</p><h4>Getting Started with Web Scraping</h4><p>If you want to get started with it, look below.</p><p>Here’s a simple Python script that demonstrates web scraping by extracting the titles of the latest articles from the front page of the New York Times website:</p><pre>import requests<br>from bs4 import BeautifulSoup<br><br>url = &#39;https://www.nytimes.com&#39;<br>response = requests.get(url)<br><br>soup = BeautifulSoup(response.text, &#39;html.parser&#39;)<br>articles = soup.find_all(&#39;h2&#39;)<br><br>for article in articles:<br>    print(article.text)</pre><p>In this script, we first import the necessary libraries: requests for making HTTP requests to the website and BeautifulSoup for parsing the HTML content.</p><p>We then define the URL of the website we want to scrape and make a GET request to that URL using the requests library. The response is stored in the response variable.</p><p>Next, we use BeautifulSoup to parse the HTML content of the response and extract all the h2 elements from the page, which typically contain the titles of the latest articles.</p><p>Finally, we loop through each h2 element and print out the text content of each one using the text attribute.</p><p>This is a very basic example of web scraping and there are many more advanced techniques and considerations to be aware of, such as handling pagination, using headers to avoid being blocked by the website, and respecting the website’s terms of service and copyright restrictions. To keep learning, “Follow” me and “clap” for my articles to keep me motivated.</p><blockquote>Your comments help us improve. Your questions help us learn.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=484f4a00d9d2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/web-scraping-why-484f4a00d9d2">Web Scraping — Why?</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scraping a Dynamic Website, Without Selenium, Part-I]]></title>
            <link>https://medium.com/geekculture/scraping-a-dynamic-website-without-selenium-part-i-c1fec0d302bd?source=rss-37c2d2b16101------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1fec0d302bd</guid>
            <category><![CDATA[dynamic-web-scraping]]></category>
            <category><![CDATA[data-collection]]></category>
            <category><![CDATA[web-scrapers]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Irfan Ahmad]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 19:34:26 GMT</pubDate>
            <atom:updated>2022-07-21T05:30:14.203Z</atom:updated>
            <content:encoded><![CDATA[<p>We, web scrapers, know to use Selenium for scraping a dynamic website. But, after some experience and exploration we find that Selenium is not always necessary.</p><p>It is simple to understand. After all all websites use some APIs or Web-hooks. Users interact with websites through GET, POST or any such request. As web scrapers we just want data from the website. And, websites load/send data from/to some database. To use/present that data, websites use APIs. We just have to find those requests, mimic them and save the data.</p><p>A few days back, I tried the same method. I had to collect Products’ data from <a href="https://www2.reservebar.com/">Reservebar</a>. But the challenge was that I had to collect all for a particular location.</p><p>On the home page, we can see categories in the header and an ‘Enter Delivery Address’ field just below the title.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSFCJezJqqw4olFoc0DZwQ.png" /><figcaption>www2.reservebar.com home page</figcaption></figure><p>So, we have 4 categories, spirits to gifts and accessories. To find products at a particular location we have to click on the location field and enter the address, then it shows a list of addresses and we have to click one to fill in the field, then click on ‘save’. This saves the location and we are able to get products for the location. Doing this adds a tag to the products showing if a product is available at the location or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ENsjwHtuoZT1cduk45Q5Q.png" /><figcaption>www2.reservebar.com category page showing show more button</figcaption></figure><p>When we open a category, it does not show all the products, rather it shows some of its products and a ‘show more’ button. To get more products we have to click on this button until we get all of the products.</p><p>Of course, this can be done with selenium, very easily.</p><p>But, I did it without selenium.</p><h3>Solution without Selenium</h3><p>Here is how I managed it without selenium.</p><p>For our purpose, getting all the products from the four categories in the header were enough. So, I just created a list of four categories.</p><pre>collections = [&#39;spirits&#39;, &#39;wine&#39;, &#39;discover&#39;, &#39;gifts-accessories&#39;]</pre><p>For URL of each category I just appended the names to our main link that is</p><pre>https://www2.reservebar.com/collections/{category}</pre><p>This would search for each link rather than clicking each link on the home page.</p><p>Using developer tools I was able to find the the request that was triggered on clicking ‘show more’ button. So, I copied that request with its headers and cookies. The cookies helped set the location.</p><h4>Using the request</h4><p>So, here is how I clicked the ‘show more’ button without actually opening a browser. Let me break the whole script into parts.</p><p>1- Following lines of code include cookies for the request</p><pre>import requestsfrom bs4 <br>import BeautifulSoup as bs<br>import pandas as pd</pre><pre>root_url = &quot;https://www2.reservebar.com&quot; # products&#39; addresses will be appended to this root URL</pre><pre>payload={} # an empty data payload</pre><pre><br># headers for our request</pre><pre>headers = {  &#39;authority&#39;: &#39;www2.reservebar.com&#39;,  &#39;accept&#39;: &#39;text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9&#39;,  &#39;accept-language&#39;: &#39;en-US,en;q=0.9&#39;,  &#39;cache-control&#39;: &#39;max-age=0&#39;,  &#39;sec-ch-ua&#39;: &#39;&quot;Chromium&quot;;v=&quot;103&quot;, &quot;.Not/A)Brand&quot;;v=&quot;99&quot;&#39;,  &#39;sec-ch-ua-mobile&#39;: &#39;?0&#39;,  &#39;sec-ch-ua-platform&#39;: &#39;&quot;Linux&quot;&#39;,  &#39;sec-fetch-dest&#39;: &#39;document&#39;,  &#39;sec-fetch-mode&#39;: &#39;navigate&#39;,  &#39;sec-fetch-site&#39;: &#39;none&#39;,  &#39;sec-fetch-user&#39;: &#39;?1&#39;,  &#39;upgrade-insecure-requests&#39;: &#39;1&#39;,  &#39;user-agent&#39;: &#39;Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36&#39;,  &#39;Cookie&#39;: &#39;__cq_dnt=1; dw_dnt=1; dwanonymous_a40f731d0711af5eb64499a73962349d=acufdphn0DuqzTqpqehaZp0DTc; dwsid=__EYAfXIo7BoEcYW1pQyOh0NcUmbp9wkncr3rR5ZPH6TknOGh6nHxPMEspRdXYKdgSkuZdsQqkrhWpEOf8P0NA==; sid=P67PVuk3mQcAmmYLM16Xkt1Sph6HWOaT9UE&#39;}</pre><p>Cookies in these headers play the role to setting the location.</p><p>2- These lines given below are lists for storing data</p><pre># list of categories<br>collections = [&#39;spirits&#39;, &#39;wine&#39;, &#39;discover&#39;, &#39;gifts-accessories&#39;] </pre><pre># list to store products&#39; links<br>products_links = []</pre><p>3- All the lines below are inside a for loop</p><pre># for each category in the categories&#39; list<br>for cat in collections:</pre><pre>    # set its URL<br>    cat_url = f&quot;https://www2.reservebar.com/collections/{cat}&quot;<br>    # send a GET request to the URL<br>    cat_res = requests.request(&quot;GET&quot;, cat_url, headers=headers, data=payload)<br>    # find the total number of results/products in that category<br>    soup = bs(cat_res.text, &#39;html.parser&#39;)<br>    more_results = soup.find(&#39;span&#39;, class_=&#39;results-span&#39;).get_text().strip().split(&#39; &#39;)[0].split(&#39;,&#39;)<br>    results = int(&#39;&#39;.join(more_results))</pre><pre>    # print the total number of products in that category<br>    print(f&quot;link: {cat_url}&quot;, &quot; results: &quot;,results)</pre><p>First I used the following line to get all the products at once.</p><pre>show_more_link = f&quot;https://www2.reservebar.com/on/demandware.store/Sites-reservebarus-Site/default/Search-UpdateGrid?cgid={cat}&amp;start={start}&amp;sz={size}&amp;selectedUrl=https%3A%2F%2Fwww2.reservebar.com%2Fon%2Fdemandware.store%2FSites-reservebarus-Site%2Fdefault%2FSearch-UpdateGrid%3Fcgid%3D{cat}%{results}start%3D{1}%{results}sz%3D{results}&quot;</pre><p>But it was still unable to load full source. So I put sent this request in parts i.e rather than loading all the products at once I loaded products in greater quantity than being loaded by the actual script. I loaded 100 products until all the products were loaded. And, for this purpose I used a nested ‘while loop’ inside the parent ‘for loop’.</p><p>The following lines are inside the main ‘For loop’</p><pre>    # counter for the number of product to start from, to load from the API<br>    start = 1<br>    # number of products to load in a single request<br>    size = 100</pre><pre>    # the while loop<br>    while True:</pre><pre>        # if start position becomes equal to greater than the total number of products, break the while loop and move forward to next category<br>        if start&gt;=results:<br>            break<br>        # the request to show more products, with variable paramaters indicated inside curly brackets<br>        show_more_link = f&quot;https://www2.reservebar.com/on/demandware.store/Sites-reservebarus-Site/default/Search-UpdateGrid?cgid={cat}&amp;start={start}&amp;sz={size}&amp;selectedUrl=https%3A%2F%2Fwww2.reservebar.com%2Fon%2Fdemandware.store%2FSites-reservebarus-Site%2Fdefault%2FSearch-UpdateGrid%3Fcgid%3D{cat}%{size}start%3D{start}%{size}sz%3D{size}&quot;<br>        </pre><pre>        # send the GET request to load more products<br>        response = requests.request(&quot;GET&quot;, show_more_link, headers=headers, data=payload)</pre><pre>        # from the response get all the products found which do not have a tag indicating not available at the location<br>        soup = bs(response.text, &#39;html.parser&#39;)<br>        all_products = soup.find_all(&#39;div&#39;, class_=&quot;product-tile&quot;)<br>        <br>        for prod in all_products:<br>            if &quot;Not available in IL&quot; in prod.get_text():<br>                ...<br>            else:<br>                a = prod.find(&#39;a&#39;)<br>                products_links.append(root_url+a[&#39;href&#39;])<br>                # print(a[&#39;href&#39;])</pre><pre>        # increment start number by 1<br>        start += 100<br>     print(&quot;number of products&#39; links: &quot;, len(products_links))</pre><p>Here ends the ‘for loop’ and products’ links scraping.</p><p>In this way I scraped nearly all the products of the categories and then saved them in a .CSV file for a record and latter use.</p><p>Here is the complete code of this application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63f068e40d17b51800a05f9a0a1ce304/href">https://medium.com/media/63f068e40d17b51800a05f9a0a1ce304/href</a></iframe><p>Latter, I did not have time to check for more requests. So I just used Selenium to scrap each product’s information for the location. Because these links were using some different kinds of requests and in combination. That’s why to save my time from here I just implemented what I already knew.</p><h3>Conclusion</h3><p>We can monitor Website’s requests for some events from developer tools and can copy them to to get data rather than using Selenium for clicking or other such request based events. But, it’s not always applicable.</p><p>Learning never ends, so I shall continue to learn, experiment and share.</p><p>If you are new, I have also written on scraping dynamic websites with selenium Part-1, Part-II, Part-III, Part-IV and Part-V.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1fec0d302bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/scraping-a-dynamic-website-without-selenium-part-i-c1fec0d302bd">Scraping a Dynamic Website, Without Selenium, Part-I</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scraping a Dynamic Website, Selenium Part-V]]></title>
            <link>https://medium.com/geekculture/scraping-a-dynamic-website-selenium-part-v-50fd5fc386cb?source=rss-37c2d2b16101------2</link>
            <guid isPermaLink="false">https://medium.com/p/50fd5fc386cb</guid>
            <category><![CDATA[dynamic-web-scraping]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[selenium-web-scraping]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[selenium-webdriver]]></category>
            <dc:creator><![CDATA[Irfan Ahmad]]></dc:creator>
            <pubDate>Sun, 17 Jul 2022 14:17:05 GMT</pubDate>
            <atom:updated>2022-07-18T05:29:14.473Z</atom:updated>
            <content:encoded><![CDATA[<p>With the passage of time developers have grown enough to overcome the challenges of Java Scripts in websites. But, that is one end. As the developers have learnt and developed a lot about scraping the websites, website developers have also developed new strategies to tackle the scrapers.</p><p>This time my challenge was to scrap a Hungarian website. Though language was not a big challenge, the website itself was a challenge to scrap data from. Here is the website I was scraping.</p><p><a href="https://hu.ryobitools.eu/">Ryobi Tools HU | Elektromos kéziszerszámok, ONE+, kertigépek, 36V</a></p><h4>What was my goal and what were the challenges here and how did I tackle them?</h4><p><strong>Goal:</strong></p><p>My goal was to get products’ details and images from the website, from almost all the menus.</p><p><strong>Challenges:</strong></p><p>1- an accept cookies alert</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ef7nRtPVKwskk92S1-WRyw.png" /><figcaption>image showing cookies handler for https://hu.ryobitools.eu</figcaption></figure><p>2- the interactive behavior of menus that is, to get the list of all menu options I had to click main menu options, then click on sub menus, then sub sub menus and so on. This was to be repeated for all main menu options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*hIPf0Js6yToBPQWgxhMH_g.gif" /><figcaption>hu.ryobitool.eu interactive menu</figcaption></figure><p>3- Session expiration: To scrap the products’ info I first collected all products’ links and then for each product’s link I scraped its info. But, due to large number of links and slow network the session used to expire after some iterations/links.</p><p><strong>Solutions:</strong></p><p>1- Cookies alert: This was easy to handle. Below lines of code just find the cookie alert and then accept them.</p><pre>def open_url(https://medium.com/self,%20url) -&gt; None:        <br>    # self.driver = Chrome()                <br>    time.sleep(0.2)<br>    self.driver.get(url)</pre><pre>    self.driver.maximize_window()        <br>    time.sleep(.1)         <br>    try:            <br>        Alert(self.driver).dismiss()        <br>    except:            <br>        ...         <br>    # cookie handler       <br>    try:            <br>        self.driver.find_element(By.ID, &#39;onetrust-accept-btn-handler&#39;).click()           <br>        time.sleep(random.choice(self.sleeps))<br>    except:<br>        ...</pre><pre>    return self.driver.current_url</pre><p>2- Interactive menus: To tackling this issue I implemented different functions. in a While loop. Here is the detailed solution.</p><pre>class Ryobi(Support):        <br>    def __init__(self) -&gt; None:<br>        super().__init__()<br>        self.ryo_ini = 0<br>        self.cat_ini = 1<br>        self.sub_cat_ini = 10<br>        self.sub_sub_cat_ini = 0<br>        self.cat_len = 0<br>        self.sub_cat_len = 0<br>        self.sub_sub_cat_len = 0<br>        self.link_counter = 0</pre><p>The scraper for this site is an instance of my Support class that I once created to scraping support links of website, I had not to make many changes.</p><p>This constructor contains some definitions, basis for my script.</p><pre>self.cat_ini =&gt; index counter for main categories<br>self.sub_cat_ini =&gt; index counter for sub-categories<br>self.sub_sub_cat_ini =&gt; index counter for sub-sub-categories<br>self.cat_len =&gt; total length counter for main categories<br>self.sub_cat_len =&gt; total length counter for sub-categories<br>self.sub_sub_cat_len =&gt; total length counter for sub-sub-categories<br>self.link_counter =&gt; counter for links</pre><p>Here is the importance of these variables.</p><p><strong>self.cat_ini</strong> is initially set to 1 that is to start from 2nd index of categories found. Because the 1st index was some irrelevant link. It will remain constant until all of its sub-categories and sub-sub-categories are scraped of their products’ links. It will increase by 1 when all sub-categories and sub-sub-categories of the main category are scraped. This will increase up to the total length of the main categories.</p><p><strong>self.sub_cat_ini,</strong> the index counter of sub-category, will remain constant until all of its sub-sub-categories are scraped of their products’ links. When all the sub-sub-categories will have been scraped, this indexer will be reset to ‘0’.</p><p><strong>self.sub_sub_cat_ini,</strong> indexer for sub-sub-categories, just increase by 1 in its keeping its parent sub-category and main category index counter.</p><p><strong>self.cat_len</strong> is the total number of main categories. This is the limit to increase the <strong>self.cat_ini.</strong> When the this main index becomes equal to main categories’ count, the loop will break and the process will end.</p><p><strong>self.sub_cat_len</strong> is the total number of sub-categories for a main category. It increments the <strong>self.cat_ini</strong> by 1 when <strong>self.sub_cat_ini</strong> becomes equal to <strong>self.sub_cat_len</strong>.</p><pre>if self.sub_cat_ini == self.sub_cat_len:<br>    self.sub_cat_ini = 0<br>    self.sub_cat_len = 0<br>    self.cat_ini += 1</pre><p><strong>self.sub_sub_cat_len</strong> is the total number of sub-sub-categories for a sub-category of a main category. <strong>self.cat_ini </strong>and<strong> self.sub_cat_ini </strong>remain constant until<strong> self.sub_sub_cat_ini</strong> becomes equal to <strong>self.sub_sub_cat_len</strong>.</p><pre>if self.sub_cat_ini == self.sub_cat_len:<br>    self.sub_cat_ini = 0<br>    self.sub_cat_len = 0<br>    self.cat_ini += 1</pre><p>Here is the full implementation as pseudo code.</p><pre>while True:<br>    get main categories<br>    if self.cat_len ==0:<br>        self.cat_len = length(main categories)<br>    categories[self.cat_ini].click() # click on the particular main category<br>    get sub-categories<br>    if self.sub_cat_len == 0:<br>        self.sub_cat_len = length(sub_categories)<br>    sub_cats[self.sub_cat_ini].click() # click open a sub-category<br>    <br>    # try to find sub-sub-categories of a sub-category<br>    sub_sub_cats = []<br>    try:<br>        sub_sub_cats = self.driver.find_elements(By.CLASS_NAME, &#39;CategoryDropdownstyles__Link-kkzqgd-9&#39;)<br>    except:<br>        ...</pre><pre>    if length(sub_sub_cats)&gt;0 and self.sub_sub_cat_len == 0:<br>        self.sub_sub_cat_len = length(sub_sub_cats)<br>    if length(sub_sub_cats)&gt;0:<br>        sub_sub_cats[self.sub_sub_cat_ini].click()<br>        print(f&#39;now on sub sub category: {self.sub_sub_cat_ini}&#39;)<br>        self.sub_sub_cat_ini += 1</pre><pre>    products = get_products from the current link, that is either from sub-categories or from sub-sub-categories</pre><pre>i = 1<br>    for link in products:<br>        if self.link_counter&gt;0:<br>            print(f&#39;saving record number: {i}, in the dataset for the link: &#39;, link)                    <br>            ryo = os.path.join(cur_dir, f&#39;scraped_data/hu.ryobytools.eu-sample.xlsx&#39;)<br>            get_details_of_the_product(link, ryo, which=&#39;ryobi&#39;)<br>            i+=1</pre><pre>    if self.sub_sub_cat_ini == self.sub_sub_cat_len:<br>        self.sub_sub_cat_ini = 0<br>        self.sub_sub_cat_len = 0<br>        self.sub_cat_ini += 1</pre><pre>    if self.sub_cat_ini == self.sub_cat_len:<br>        self.sub_cat_ini = 0<br>        self.sub_cat_len = 0<br>        self.cat_ini += 1</pre><pre>    if self.cat_ini == self.cat_len:<br>        break</pre><p>3- The third problem is dealt in this snippet:</p><pre>try:<br>    self.driver.get(url)<br>except:<br>    self.driver.start_session({})<br>    self.driver.maximize_window()<br>    time.sleep(0.2)<br>    self.driver.get(url)</pre><p>So, in this way I got the solution. <a href="https://github.com/Irfan-Ahmad-byte/hungarian_scraping_proj">Here</a> is the link to my my repository that contains my solution. I used different solutions for this project. The repository also contains setup to use selenium hub through docker, this was my priority. It also includes setup for standalone selenium.</p><p>If you are new here, you can check <a href="https://medium.com/swlh/scraping-a-dynamic-web-page-its-selenium-da161999c975?source=your_stories_page-------------------------------------">Part-I</a>, <a href="https://medium.com/geekculture/scraping-a-dynamic-website-selenium-part-ii-1f30a4b59285?source=your_stories_page-------------------------------------">Part-II</a>, <a href="https://medium.com/geekculture/scraping-a-dynamic-website-selenium-part-iii-7138d2a3131?source=your_stories_page-------------------------------------">Part-III</a> and <a href="https://medium.com/geekculture/scraping-dynamic-websites-through-remote-webdrivers-selenium-part-iv-424b6a9cc02d?source=your_stories_page-------------------------------------">Part-IV</a> in this series.</p><p>Next I’ll post an article in the series</p><blockquote>Scraping a Dynamic Website, But it’s not Selenium.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50fd5fc386cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/scraping-a-dynamic-website-selenium-part-v-50fd5fc386cb">Scraping a Dynamic Website, Selenium Part-V</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Solve Captcha with Python?]]></title>
            <link>https://medium.com/geekculture/how-to-solve-captcha-with-python-80959653dba2?source=rss-37c2d2b16101------2</link>
            <guid isPermaLink="false">https://medium.com/p/80959653dba2</guid>
            <category><![CDATA[solve-captcha]]></category>
            <category><![CDATA[python-selenium]]></category>
            <category><![CDATA[selenium-webdriver]]></category>
            <category><![CDATA[how-to-solve-captcha]]></category>
            <category><![CDATA[python-web-scraping]]></category>
            <dc:creator><![CDATA[Irfan Ahmad]]></dc:creator>
            <pubDate>Sun, 26 Dec 2021 16:01:12 GMT</pubDate>
            <atom:updated>2021-12-26T16:01:12.395Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scraping A Dynamic Website, Part-V: Handling Captcha</h3><p>Captcha are a big hurdle when we try to scrap some really secure website.</p><figure><img alt="image showing I’m not a robot" src="https://cdn-images-1.medium.com/max/795/1*Z4PCXy0JfcbGyaiMnRLbTA.jpeg" /><figcaption>I’m not a robot</figcaption></figure><p>It is said that captcha can be avoided by implementing ‘webdriver waits’ and by reducing pooling frequency. But in my case, it never worked.</p><h4>How Did I Solve Captcha Then!</h4><p>Here are some options that I could implement to tackle captcha;<br>1- put waits and set less polling frequency (never worked for me)<br>2- use machine learning models (a costly and resource taking method)<br>3- use speech-to-text or text-to-speech options (easy one, but not always available)<br>4- use some captcha solving service (I found it to be a best option. It’s cost + resource effective.)</p><p>So, I selected option 4. Here is how it works.</p><h4>Solving Captcha</h4><p>Just follow the steps.</p><p>1- Create an account at <a href="https://anti-captcha.com/">https://anti-captcha.com/</a> and get your ACCESS TOKEN.<br>2- Download the ‘anticaptcha’ plugin for your browser i.e, chrome, firefox etc. from <a href="https://antcpt.com/eng/download/google-chrome-options/manual-crx.html">here</a>. Keep this plugin in your working directory to prevent access problems.<br>3- Add this in your script</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90d0e209cdb96b8f08d21f22ab7b09a6/href">https://medium.com/media/90d0e209cdb96b8f08d21f22ab7b09a6/href</a></iframe><p>Put this before you start scraping in your script.</p><p>That’s all. It worked for me. And, I hope it will work for you too.</p><p>Let me be clear, it was not sponsored writing for ‘anti-captcha.com’. I wrote this because I found it useful.</p><p>Regards</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80959653dba2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-solve-captcha-with-python-80959653dba2">How to Solve Captcha with Python?</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scraping Dynamic Websites Through Remote WebDrivers, Selenium Part-IV]]></title>
            <link>https://medium.com/geekculture/scraping-dynamic-websites-through-remote-webdrivers-selenium-part-iv-424b6a9cc02d?source=rss-37c2d2b16101------2</link>
            <guid isPermaLink="false">https://medium.com/p/424b6a9cc02d</guid>
            <category><![CDATA[python-selenium]]></category>
            <category><![CDATA[selenium-webdriver]]></category>
            <category><![CDATA[dynamic-web-scraping]]></category>
            <category><![CDATA[selenium-remote-webdriver]]></category>
            <category><![CDATA[selenium-container]]></category>
            <dc:creator><![CDATA[Irfan Ahmad]]></dc:creator>
            <pubDate>Sat, 25 Dec 2021 20:01:04 GMT</pubDate>
            <atom:updated>2021-12-25T20:01:04.657Z</atom:updated>
            <content:encoded><![CDATA[<p>In first three parts I used selenium locally for web scraping. This time I am going to use a ‘Remote WebDriver’ to scrap some data.</p><h4>Why Remote WebDriver?</h4><p>Sometimes we need to run our scraper script on some CLI servers. So, selenium’s webdrivers won’t work there. In that case we may use remote webdriver, a webdriver hosted somewhere else. We just need to access it through docker.</p><h4>Let’s Start</h4><p>All the selectors and the script is same. The only change is the webdriver’s location. Let’s have a look at our script employing the remote driver.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cf61619754be30ee7bb87f871d63e0b/href">https://medium.com/media/1cf61619754be30ee7bb87f871d63e0b/href</a></iframe><p>The script contains a ‘scraper’ class with a method ‘open_support’. The ‘open_support’ takes two arguments, an object of ‘scraper’ class and a name of the platform. The method will then find a support URL of the platform specified in the name.</p><h4>What’s New Here?</h4><p>While scraping through local selenium we defined driver like this.</p><pre>from selenium import webdriver<br>from selenium.webdriver import Chrome, ChromeOptions, Remote, FirefoxOptions</pre><p>In the current script, we defined the ‘driver’ in the constructor method (__init__ method) like this;</p><pre>self.driver = Remote( command_executor=’http://localhost:4444/wd/hub’, options=options )</pre><p>The only change we made for web scraping remotely is in defining ‘driver’.</p><p>In ‘Remote’ the argument ‘command_executor’ refers to the URL or address of the <strong>“container”</strong> that hosts ‘selenium’.</p><blockquote>Container!!!</blockquote><blockquote>Briefly, a container is like a PC that may be anywhere on Earth. It’s a PC without any hardware to care about. More on containers, may be latter.</blockquote><p>We are done with scripting. Now we need a container that we will access through ‘command_executor’.</p><h4>Let’s Prepare Container for Remote WebDriver</h4><p>1- First we need to install ‘Docker’, a famous container provider. A tutorial about ‘How to install docker in Ubuntu 20.04’ can be found <a href="https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-20-04">here</a>.<br>2- Pull selenium container for chrome with</p><pre>docker pull selenium/standalone-chrome</pre><p>While pulling the container image, the Terminal displays some details about the image being pulled. It also displays a ‘tag’ showing the version of the image, usually latest if not specified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXJnfhoG7Ti-hYT1yFQc6A.png" /><figcaption>image pulling a docker image</figcaption></figure><p>The image above is pulling some docker image. In its second line</p><pre>Using default tag: latest</pre><p>displays its tag as ‘latest’. <br>For our ‘selenium’ projects we call this tag as ‘flag’.<br>3- Start the docker service with</p><pre>sudo service docker start</pre><p>4- Initiate the container image with</p><pre>docker run -d -p 4444:4444 --shm-size=&quot;2g&quot; selenium/standalone-chrome:latest</pre><p>You may replace ‘latest’ with <strong>flag</strong> of your image.<br>Detailed instructions about selenium containers can be found <a href="https://github.com/SeleniumHQ/docker-selenium">here</a>.</p><h4>Let’s Run the Scraper</h4><pre>&gt; python scraper.py</pre><p>6- When the scraper is done, it’s better to stop the container. You can either first stop the container and then docker service</p><pre>docker container ls</pre><p>Copy container id from the output then type the following and press enter.</p><pre>docker stop container-id  </pre><p>Replace container-id with the id you just copied.</p><pre>sudo service docker stop # stop docker service</pre><p>OR directly stop the docker service.</p><pre>sudo service docker stop</pre><p>This is it for today. We used a remote webdriver for scraping websites.</p><p>If you have not yet read then you may like to read Scraping A Dynamic Website, Selenium <a href="https://medium.com/swlh/scraping-a-dynamic-web-page-its-selenium-da161999c975?source=user_profile---------6-------------------------------">Part-I</a>, <a href="https://medium.com/geekculture/scraping-a-dynamic-website-selenium-part-ii-1f30a4b59285?source=user_profile---------4-------------------------------">Part-II</a> and <a href="https://medium.com/geekculture/scraping-a-dynamic-website-selenium-part-iii-7138d2a3131?source=user_profile---------3-------------------------------">Part-III</a>.</p><p>Happy Scraping!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=424b6a9cc02d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/scraping-dynamic-websites-through-remote-webdrivers-selenium-part-iv-424b6a9cc02d">Scraping Dynamic Websites Through Remote WebDrivers, Selenium Part-IV</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>