<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged scraping</title>
<link>https://coderlegion.com/tag/scraping</link>
<description>Powered by Question2Answer</description>
<item>
<title>Innovative Projects for Python Developers</title>
<link>https://coderlegion.com/11992/innovative-projects-for-python-developers</link>
<description>&lt;p&gt;As a Python developer, staying relevant and improving your skills is vital. Here are some innovative project ideas that cater to various experience levels and can help you tackle real-world challenges.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Personal Finance Tracker&lt;/strong&gt;&lt;br&gt;
Develop an application that allows users to track expenses, income, and savings goals. Integrating data visualization libraries such as Matplotlib or Plotly can make representation of financial data intuitive and engaging. Consider adding features like budgeting alerts or trend analysis to enrich user experience.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Chatbot with NLP&lt;/strong&gt;&lt;br&gt;
Create a chatbot that utilizes Natural Language Processing (NLP) to provide customer support or assist with common queries. Use libraries like NLTK or SpaCy to parse and understand user input. You can enhance it by integrating it with messaging platforms like Slack or Telegram.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Web Scraping Tool&lt;/strong&gt;&lt;br&gt;
Build a tool that extracts timely information from websites like news sources or e-commerce platforms. This project can sharpen your skills in data retrieval and manipulation using libraries like BeautifulSoup and Requests. Make sure to respect website scraping policies (robots.txt) while developing.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Machine Learning for Image Classification&lt;/strong&gt;&lt;br&gt;
Leverage frameworks like TensorFlow or PyTorch to build a model that classifies images. This could range from identifying dog breeds in photos to distinguishing between various plant species. Experiment with different algorithms and datasets to deepen your understanding.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Recipe Recommendation System&lt;/strong&gt;&lt;br&gt;
Create an application that provides users with meal suggestions based on available ingredients. Use Python's data handling capabilities alongside web APIs like Spoonacular for fetching recipes, allowing your app to be both functional and user-friendly.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Serverless Web Application&lt;/strong&gt;&lt;br&gt;
Explore serverless architecture by building a web application using AWS Lambda and API Gateway. This project will help you grasp the concepts of cloud computing and scalability without the hassle of managing servers directly.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Blog Platform with Markdown Support&lt;/strong&gt;&lt;br&gt;
Develop a full-stack blog platform that uses Python Flask or Django for backend and a JavaScript framework for the frontend. Incorporating Markdown for blog posts enables users to format their articles easily, which could enhance the overall publishing experience.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Each project not only strengthens your coding skills but also adds impressive projects to your portfolio. Mix and match these ideas or combine aspects from different ones to create a unique implementation tailored to your interests. Remember to keep testing and iterating as feedback can lead to enhancements that may not have been initially considered.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/11992/innovative-projects-for-python-developers</guid>
<pubDate>Sat, 21 Feb 2026 10:58:20 +0000</pubDate>
</item>
<item>
<title>Mastering Web Scraping with Python</title>
<link>https://coderlegion.com/379/mastering-web-scraping-with-python</link>
<description>&lt;p&gt;Data gathering is made possible via &lt;strong&gt;web scraping&lt;/strong&gt;, which automates the process of extracting information from websites. Powerful libraries like &lt;strong&gt;Scrapy&lt;/strong&gt;, &lt;strong&gt;BeautifulSoup&lt;/strong&gt;, and &lt;strong&gt;Selenium&lt;/strong&gt;, together with its straightforward syntax, make &lt;strong&gt;Python&lt;/strong&gt; the best choice. For &lt;strong&gt;analysis&lt;/strong&gt; purposes, such as pricing tracking, review gathering, or news tracking, proficiency with web scraping is essential. In this article, we'll cover web scraping basics, usage of tools like BeautifulSoup, Selenium, and Scrapy and &lt;strong&gt;Requests&lt;/strong&gt; for &lt;strong&gt;API scraping&lt;/strong&gt;.&lt;/p&gt;
&lt;h2 id=&quot;understanding-web-scraping&quot;&gt;Understanding Web Scraping&lt;/h2&gt;
&lt;p&gt;Web scraping makes use of a variety of tools and techniques to extract information.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tools&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;BeautifulSoup&lt;/strong&gt;: This Python module parses HTML and XML documents and can easily extract information by building a parse tree from the source code of webpages. Learn more &lt;a rel=&quot;nofollow&quot; href=&quot;https://beautiful-soup-4.readthedocs.io/en/latest/&quot;&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Scrapy&lt;/strong&gt;: It is an effective Python library that uses self-contained crawlers called spiders, that extract data from websites. Learn more &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.scrapy.org/en/latest/&quot;&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Selenium&lt;/strong&gt;: It's a browser automation tool that runs a web browser in a regular manner by scraping dynamic material generated using JavaScript. Learn more &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.selenium.dev/documentation/&quot;&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Requests&lt;/strong&gt;: It is an HTTP library for Python that allows you to send and handle HTTP requests and responses. Learn more &lt;a rel=&quot;nofollow&quot; href=&quot;https://requests.readthedocs.io/en/latest/&quot;&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Legal Considerations&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Many websites' Terms of Service (TOS) specifically ban scraping.&lt;/li&gt;
&lt;li&gt;Scraping data may breach copyright laws by extracting and using material without authorization.&lt;/li&gt;
&lt;li&gt;Always examine and respect a website's &lt;code&gt;robots.txt&lt;/code&gt; file, which specifies which portions of the site can and cannot be scraped.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;installing-and-configuring-web-scraping-libraries&quot;&gt;Installing and Configuring Web Scraping Libraries&lt;/h2&gt;
&lt;div class=&quot;div-blue&quot;&gt; &lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt; &lt;span class=&quot;alert-body&quot;&gt; The following codes are run on the terminal or in a code editor or IDE like Visual Studio Code.&lt;/span&gt; &lt;/div&gt;
&lt;p&gt;The libraries can be installed as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;BeautifulSoup&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  pip install beautifulsoup4
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Scrapy&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  pip install scrapy
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Selenium&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  pip install selenium
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Requests&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  pip install requests
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;div-red&quot;&gt; &lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt; &lt;span class=&quot;alert-body&quot;&gt; Make sure `pip` is installed on your system.&lt;/span&gt; &lt;/div&gt;
&lt;p&gt;Working in a virtual environment is recommended since it reduces conflicts with other projects and helps manage dependencies.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Creating a virtual environment:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python -m venv sampenv
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Activation:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;On Windows:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  sampenv\Scripts\activate
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;On Linux and macOS:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  source sampenv/bin/activate
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;div-green&quot;&gt; &lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt; &lt;span class=&quot;alert-body&quot;&gt; Working in a virtual environment is recommended since it reduces conflicts with other projects and helps manage dependencies.&lt;/span&gt; &lt;/div&gt;
&lt;h2 id=&quot;basic-web-scraping-with-beautifulsoup&quot;&gt;Basic Web Scraping with BeautifulSoup&lt;/h2&gt;
&lt;p&gt;BeautifulSoup is a Python library that works on HTML and XML files to extract data by creating a parse tree from a page source to traverse and find elements, attributes or text using methods like &lt;code&gt;find()&lt;/code&gt; and &lt;code&gt;find_all()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Extracting Tags&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;You can extract HTML tags like &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;a&amp;gt;&lt;/code&gt;, etc. using &lt;code&gt;find()&lt;/code&gt; and &lt;code&gt;find_all()&lt;/code&gt; methods.&lt;br&gt;
Syntax:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;find()&lt;/code&gt;: soup.find(tag_name, attrs={})&lt;/li&gt;
&lt;li&gt;&lt;code&gt;find_all()&lt;/code&gt;: soup.find_all(tag_name, attrs={})&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Extracting Attributes&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;HTML tag attributes can be extracted using the &lt;code&gt;get()&lt;/code&gt; method or a dictionary-style access from the &lt;code&gt;find()&lt;/code&gt; method.&lt;br&gt;
Syntax:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;tag = soup.find('tag_name')&lt;/li&gt;
&lt;li&gt;&lt;code&gt;get()&lt;/code&gt;: tag.get('attr_name')&lt;/li&gt;
&lt;li&gt;Dictionary-style access: tag['attr_name']&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Extracting Text&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Text contents of HTML elements can be accessed using the &lt;code&gt;get_text()&lt;/code&gt; method or the  &lt;code&gt;.text&lt;/code&gt; attribute.&lt;br&gt;
Syntax:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;tag = soup.find('tag_name')&lt;/li&gt;
&lt;li&gt;&lt;code&gt;get_text()&lt;/code&gt;: tag.get_text()&lt;/li&gt;
&lt;li&gt;&lt;code&gt;.text&lt;/code&gt;: tag.text&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Let's take a look at an example to understand the methods better:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;from bs4 import BeautifulSoup

html_content = &quot;&quot;&quot;
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang=&quot;en&quot;&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset=&quot;UTF-8&quot;&amp;gt;
    &amp;lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&amp;gt;
    &amp;lt;title&amp;gt;Grocery List&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;div id=&quot;content&quot;&amp;gt;
        &amp;lt;h1&amp;gt;Welcome to my List&amp;lt;/h1&amp;gt;
        &amp;lt;p&amp;gt;This is a list of my &amp;lt;strong&amp;gt;grocery items&amp;lt;/strong&amp;gt;.&amp;lt;/p&amp;gt;
        &amp;lt;ul&amp;gt;
            &amp;lt;li&amp;gt;Milk&amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt;Bread&amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt;Carrots&amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt;Butter&amp;lt;/li&amp;gt;
        &amp;lt;/ul&amp;gt;
        &amp;lt;a href=&quot;https://samp.com&quot;&amp;gt;Sample&amp;lt;/a&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&quot;&quot;&quot;

soup = BeautifulSoup(html_content, 'html.parser')
title_tag = soup.find('title')     # extracts Title tag
h1_tag = soup.find('h1')     # extracts H1 tag
p_tag = soup.find('p')
ul_tag = soup.find('ul')
a_tag = soup.find('a')

print(&quot;Title:&quot;, title_tag.text)    # extracts text from Title tag
print(&quot;H1:&quot;, h1_tag.get_text())    # extracts text from H1 tag
print(&quot;Paragraph:&quot;, p_tag.text)
print(&quot;List Items:&quot;)
for li in ul_tag.find_all('li'):    # extracts list items
    print(&quot;-&quot;, li.text)
print(&quot;Link Href:&quot;, a_tag['href'])    # displays 'href' attribute's value
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The code contains a sample HTML script, from which tags, attributes and texts are extracted.&lt;/p&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=5172687390427303573&quot; alt=&quot;beautifulsoup&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;scraping-dynamic-websites-with-selenium&quot;&gt;Scraping Dynamic Websites with Selenium&lt;/h2&gt;
&lt;p&gt;Selenium is a great tool for scraping dynamic webpages using JavaScript. It enables button clicks, form submissions, and page navigation by allowing programmatic control of a web browser. In order to use Selenium, you need to set up Selenium WebDriver for your browser.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Google Chrome&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Download ChromeDriver from chromedriver.chromium.org&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Set up ChromeDriver:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  from selenium import webdriver
  from selenium.webdriver.chrome.service import Service
  from webdriver_manager.chrome import ChromeDriverManager
  service = Service(ChromeDriverManager().install())
  driver = webdriver.Chrome(service=service)
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Mozilla Firefox&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Download GeckoDriver from github.com/mozilla/geckodriver/releases.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Set up GeckoDriver:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  from selenium import webdriver
  from selenium.webdriver.firefox.service import Service
  from webdriver_manager.firefox import GeckoDriverManager
  service = Service(GeckoDriverManager().install())
  driver = webdriver.Firefox(service=service)
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Microsoft Edge&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Download EdgeDriver from developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Set up EdgeDriver:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  from selenium import webdriver
  from selenium.webdriver.edge.service import Service
  from webdriver_manager.microsoft import EdgeChromiumDriverManager
  service = Service(EdgeChromiumDriverManager().install())
  driver = webdriver.Edge(service=service)
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Extracting Elements&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;find_element() Method&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;To discover a single web element that meets the given criteria, use the &lt;code&gt;find_element()&lt;/code&gt; function.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Syntax: &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;element = driver.find_element(By.ID, 'ID_value')&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;find_elements() Method&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Use the &lt;code&gt;find_elements()&lt;/code&gt; function to find numerous web items that fit certain criteria. It will return a list of WebElement objects that represent all matched things.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Syntax: &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;elements = driver.find_elements(By.CLASS_NAME, 'Class_name_val')&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;get_attribute() Method&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;It retrieves the value of an attribute like &lt;code&gt;href&lt;/code&gt;, &lt;code&gt;src&lt;/code&gt;, etc. from a web element.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Syntax:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;link = driver.find_element(By.TAG_NAME, 'Tag_value')&lt;/li&gt;
&lt;li&gt;href_value = link.get_attribute('attr_value')&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;text Property&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;It extracts text content from elements like paragraphs, headings, or list items.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Syntax:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;element = driver.find_element(By.CLASS_NAME, 'Class_val')&lt;/li&gt;
&lt;li&gt;txt = element.text&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;send_keys() Method&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;This method is helpful for input fields since it mimics typing into text fields or search boxes.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Syntax:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;inp_box = driver.find_element(By.NAME, 'Name_value')&lt;/li&gt;
&lt;li&gt;inp_box.send_keys('Hello!')&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;click() Method&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;This method is used to click buttons, links, checkboxes, or any clickable element.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Syntax:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;button = driver.find_element(By.ID, 'ID_value')&lt;/li&gt;
&lt;li&gt;button.click()&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;execute_script() Method&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;JavaScript code for advanced interactions, such as scrolling and event triggering, is executed via this method.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Syntax:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;driver.execute_script(&quot;your_JS_code&quot;)&lt;/li&gt;
&lt;li&gt;Example for scrolling: &lt;/li&gt;
&lt;li&gt;driver.execute_script(&quot;window.scrollTo(0, document.body.scrollHeight);&quot;)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Let's take a look at an example to understand it better:&lt;/p&gt;
&lt;p&gt;samplepage.html:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang=&quot;en&quot;&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset=&quot;UTF-8&quot;&amp;gt;
    &amp;lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&amp;gt;
    &amp;lt;title&amp;gt;Sample Page for Selenium&amp;lt;/title&amp;gt;
    &amp;lt;script&amp;gt;
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('dynamicButton').addEventListener('click', function() {
                document.getElementById('dynamicContent').innerHTML = '&amp;lt;p class=&quot;dynamicText&quot;&amp;gt;I hope you are doing well.&amp;lt;/p&amp;gt;';
                document.getElementById('dynamicContent').innerHTML += '&amp;lt;a href=&quot;https://samp.com&quot; class=&quot;dynamicLink&quot;&amp;gt;Example Link&amp;lt;/a&amp;gt;';
            });
        });
    &amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;h1 id=&quot;pageTitle&quot;&amp;gt;Welcome!&amp;lt;/h1&amp;gt;
    &amp;lt;input type=&quot;text&quot; id=&quot;inputField&quot; name=&quot;inputName&quot; placeholder=&quot;Enter something...&quot;&amp;gt;
    &amp;lt;button id=&quot;dynamicButton&quot;&amp;gt;Load Content&amp;lt;/button&amp;gt;
    &amp;lt;div id=&quot;dynamicContent&quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Python script for data extraction:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.get(&quot;samplepage.html&quot;)    # opens the webpage

wait = WebDriverWait(driver, 20)
page_title = wait.until(EC.presence_of_element_located((By.ID, 'pageTitle')))     # waits for 20 sec for page to load
page_title = driver.find_element(By.ID, 'pageTitle')
print(&quot;Page Title:&quot;, page_title.text)
input_field = driver.find_element(By.NAME, 'inputName')
input_field.send_keys('Hello, Alayne!')    # enters given data
print(&quot;Input Field Value:&quot;, input_field.get_attribute('value'))
dynamic_button = driver.find_element(By.ID, 'dynamicButton')
dynamic_button.click()    # clicks the button
wait = WebDriverWait(driver, 10)
dynamic_text = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'dynamicText')))
print(&quot;Dynamic Text:&quot;, dynamic_text.text)
dynamic_link = driver.find_element(By.CLASS_NAME, 'dynamicLink')
print(&quot;Dynamic Link Href:&quot;, dynamic_link.get_attribute('href'))
driver.execute_script(&quot;window.scrollTo(0, document.body.scrollHeight);&quot;)    # scrolls
driver.quit()    # close the browser
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The code extracts data from the given JavaScript file and also enters data into the text field, clicks a button and scrolls through the webpage.&lt;/p&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1675114351117885347&quot; alt=&quot;selenium&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;scraping-with-scrapy&quot;&gt;Scraping with Scrapy&lt;/h2&gt;
&lt;p&gt;A Python-based framework for online crawling and scraping, Scrapy provides a number of tools for effectively extracting data from webpages. It effortlessly pulls data, follows links, and manages requests.&lt;br&gt;
An item is a container that item pipelines use to process and store scraped data. An item pipeline component is any Python class that implements a method on items.&lt;/p&gt;
&lt;p&gt;Let's understand how to set up and define pipelines in for a Scrapy project using an example. We will be scraping &lt;a rel=&quot;nofollow&quot; href=&quot;http://quotes.toscrape.com&quot;&gt;this&lt;/a&gt; webpage&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Setting up Scrapy Projects and Defining Item Pipelines&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Open your terminal and go to the directory where you want to create a Python project.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Run the following command to create a Scrapy project consisting of files necessary for configuring the project.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; scrapy startproject scrapy_test
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This creates a Scrapy project named &lt;code&gt;scrapy_test&lt;/code&gt;.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Go to &lt;code&gt;items.py&lt;/code&gt; in the &lt;code&gt;scrapy_test&lt;/code&gt; folder. Here, you'll define a Scrapy item class, acting as a blueprint for your extracted data. Use &lt;code&gt;scrapy.Field()&lt;/code&gt; to create field instances capable of storing any data type.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; import scrapy
 class  ScrapyTestItem(scrapy.Item):
 text = scrapy.Field()
 author = scrapy.Field()
 tags = scrapy.Field()
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This code creates &lt;code&gt;text&lt;/code&gt;, &lt;code&gt;author&lt;/code&gt; and &lt;code&gt;tags&lt;/code&gt; fields to store data from the webpage.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;To set up the project settings, navigate to &lt;code&gt;settings.py&lt;/code&gt;. This is where you design and configure the order of execution for the scraped item processing pipelines. Lower values indicate higher priority.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; ITEM_PIPELINES = {
 'scrapy_test.pipelines.JsonWriterPipeline': 300,
 'scrapy_test.pipelines.HtmlWriterPipeline': 800,
 }
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This ensures that &lt;code&gt;JsonWriterPipeline&lt;/code&gt; executes before &lt;code&gt;HtmlWriterPipeline&lt;/code&gt;. These pipelines are defined in the next step.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Navigate to &lt;code&gt;pipelines.py&lt;/code&gt;. This file handles data processing, including cleansing, verifying, storing, and exporting. Multiple pipelines can be defined here.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; import json
 class JsonWriterPipeline:
     def open_spider(self, spider):
         self.file = open('quotes.json', 'w')

     def close_spider(self, spider):
         self.file.close()

     def process_item(self, item, spider):
         line = json.dumps(dict(item), ensure_ascii=False) + &quot;\n&quot;     # extracted data is converted to JSON formatted string, and non-ASCII characters are handled properly.
         self.file.write(line)
         return item

 class HtmlWriterPipeline:
     def open_spider(self, spider):
         self.file = open('quotes.html', 'w')
         self.file.write('&amp;lt;html&amp;gt;&amp;lt;body&amp;gt;&amp;lt;ul&amp;gt;')

     def close_spider(self, spider):
         self.file.write('&amp;lt;/ul&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;')
         self.file.close()

     def process_item(self, item, spider):
         self.file.write(f&quot;&amp;lt;li&amp;gt;&amp;lt;p&amp;gt;{item['text']}&amp;lt;/p&amp;gt;&amp;lt;p&amp;gt;{item['author']}&amp;lt;/p&amp;gt;&amp;lt;p&amp;gt;{', '.join(item['tags'])}&amp;lt;/p&amp;gt;&amp;lt;/li&amp;gt;&quot;)     
         return item
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This code formats the fields and stores the extracted data into two files, &lt;code&gt;quotes.json&lt;/code&gt; and &lt;code&gt;quotes.html&lt;/code&gt;.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Open &lt;code&gt;scrapy_test/spiders&lt;/code&gt;, then create &lt;code&gt;scrapy_code.py&lt;/code&gt;. This file will include spider classes to define URLs to crawl, process answers, and retrieve data using XPath or CSS selectors. The item classes in &lt;code&gt;items.py&lt;/code&gt; are used by the spider.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; import scrapy
 from scrapy_test.items import ScrapyTestItem

 class QuotesSpider(scrapy.Spider):
     name = 'quotes'
     start_urls = [http://quotes.toscrape.com]

     def parse(self, response):
         for quote in response.css('div.quote'):
             item = ScrapyTestItem()
             item['text'] = quote.css('span.text::text').get()
             item['author'] = quote.css('span small::text').get()
             item['tags'] = quote.css('div.tags a.tag::text').getall()
             yield item
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This code defines a spider named &lt;code&gt;quotes&lt;/code&gt;. Using a CSS selector, it selects all elements with the class &lt;code&gt;quote&lt;/code&gt; and creates a &lt;code&gt;ScrapyTestItem&lt;/code&gt; instance for each. The &lt;code&gt;get()&lt;/code&gt; method retrieves the text content and stores it in the respective fields.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;In your terminal, navigate to the root directory of the project (&lt;code&gt;scrapy_test&lt;/code&gt;) and run the command:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; scrapy crawl quotes
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Where &lt;code&gt;quotes&lt;/code&gt; is the spider we created.&lt;/p&gt;
&lt;p&gt;The extracted data is stored in &lt;code&gt;quotes.json&lt;/code&gt; and &lt;code&gt;quotes.html&lt;/code&gt; in the project's root directory.&lt;/p&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1288941435301189476&quot; alt=&quot;jsonfile&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=649287658806791186&quot; alt=&quot;htmlfile&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;scraping-apis-and-json-data&quot;&gt;Scraping APIs and JSON Data&lt;/h2&gt;
&lt;p&gt;Scraping APIs provide an organized way to obtain structured data. These APIs make endpoints available for accessing structured data in formats like XML and JSON. Using Requests, you may retrieve the required data by submitting queries to these endpoints and interpreting the returned responses.&lt;br&gt;
Accessing APIs might involve the usage of API keys or tokens. Keys or tokens are specified in the &lt;code&gt;request header&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Making HTTP Requests and Accessing APIs&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Acquire the API key or token by generating the key/token in the platform of your choice.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Define the URL of the webpage you want to scrape and include the key/token in the request header. Also mention the content type.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; url = https://website_name.com/data
 api_key = 'abcxyz'
 header = { 'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json' }
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Send an HTTP GET request to the specified URL with the provided headers using the &lt;code&gt;get()&lt;/code&gt; method. It returns a &lt;code&gt;Response&lt;/code&gt; object containing the server's response to the HTTP request, which can be used to extract the status code, content, etc.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; response = requests.get(url, headers=header)
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the &lt;code&gt;status code&lt;/code&gt; of the response is 200, the request was successful and the contents can be extracted in text or JSON format.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; if response.status_code == 200:
     print(response.headers)
     print(response.text)    # or response.json()
 else:
     print(f&quot;Error: {response.status_code}&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Let's take a simple example using the URL '&lt;a rel=&quot;nofollow&quot; href=&quot;https://jsonplaceholder.typicode.com/todos/12&quot;&gt;https://jsonplaceholder.typicode.com/todos/12&lt;/a&gt;'&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;    import requests
    url = 'https://jsonplaceholder.typicode.com/todos/12'
    header = {'Content-type': 'application/json'}
    response = requests.get(url, headers=header)
    if response.status_code == 200:
        print(response.headers)
        print(response.json())
    else:
        print(f&quot;Error: {response.status_code}&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This code does not involve the use of keys/tokens.&lt;/p&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14171267328091723183&quot; alt=&quot;apioutput&quot;&gt;&lt;/p&gt;
&lt;p&gt;You can also use &lt;code&gt;Requests&lt;/code&gt; to download ZIP file. For example, to download a Kaggle dataset:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import os
import requests

key = '82jfvyg3j4jngjr'    # Kaggle API key
dataset_url = 'https://www.kaggle.com/datasets/vivek468/superstore-dataset-final'
save_path = 'C:\\Downloads'    # replace with the path you want to store the file in

response = requests.get(dataset_url, headers={'Authorization': f'Bearer {key}'}, stream=True)
if response.status_code == 200:
    with open(os.path.join(save_path, 'dataset.zip'), 'wb') as f:    # download the file
        for chunk in response.iter_content(chunk_size=1024):
            f.write(chunk)
    print('Download successful.')
else:
    print('Failed to download dataset. Status code:', response.status_code)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17485878408146926284&quot; alt=&quot;apikeyzip1&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17938138653251734046&quot; alt=&quot;apikeyzip2&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Thus, a potent method for obtaining data from websites is &lt;strong&gt;Web Scraping&lt;/strong&gt;, which makes it possible to &lt;strong&gt;gather&lt;/strong&gt; and &lt;strong&gt;analyze&lt;/strong&gt; data effectively. The &lt;strong&gt;requests&lt;/strong&gt; library, &lt;strong&gt;BeautifulSoup&lt;/strong&gt;, &lt;strong&gt;Selenium&lt;/strong&gt;, and &lt;strong&gt;Scrapy&lt;/strong&gt; provide special benefits for various scraping requirements and enable developers to explore the web and retrieve important data easily. I encourage you to explore these tools further to unlock the full potential of web scraping to interact with and analyze web data.&lt;/p&gt;
</description>
<category>Automation</category>
<guid isPermaLink="true">https://coderlegion.com/379/mastering-web-scraping-with-python</guid>
<pubDate>Thu, 27 Jun 2024 21:44:52 +0000</pubDate>
</item>
</channel>
</rss>