Summary
This course teaches Python for automating everyday tasks, including web scraping, creating reports, and interacting with websites. It covers using libraries like Pandas for data extraction from HTML tables and CSVs, and Camelot for PDF table extraction. The course also delves into HTML basics, XPath for element selection, and Selenium for browser automation, including headless mode and scheduling scripts. The ultimate goal is to equip learners with practical automation skills using Python.
Key Insights
Pandas can read CSV files directly from a URL using read_csv.
The 'pd.read_csv(url)' function can be used to directly download and parse a CSV file from a given web address. This eliminates the need for manual downloading and is useful for accessing data stored online.
Attributes like 'class' and 'id' are critical for targeting specific elements during scraping.
Attributes, particularly 'class' and 'id', provide unique identifiers or categories for HTML elements. These are essential for precisely selecting the desired data points when scraping a webpage.
Execute Selenium scripts in headless mode by configuring Chrome options.
To run browser automation without a visible UI, configure Chrome options by importing 'Options' from 'selenium.webdriver.chrome.options', creating an 'options' object, setting 'options.headless = True', and passing this object to the WebDriver.
Schedule Python scripts to run automatically at specific times using OS tools.
Python scripts can be scheduled to execute at desired intervals (e.g., daily) using operating system task schedulers (like Task Scheduler on Windows or cron on Linux/macOS). This requires converting the .py file to an executable.
Sections
Introduction to Python Automation
Learn Python to automate tasks like creating Excel reports, sending texts, and web scraping.
This course will teach you how to use Python to automate various everyday tasks. Examples include generating Excel reports, sending text messages, extracting tables from websites, and interacting with web pages. The course utilizes several Python automation libraries through a series of projects.
Course instructor Frank Andrade is a data scientist and experienced teacher.
The course was created by Frank Andrade, who is a data scientist with considerable teaching experience. Learners are encouraged to check the description for a link to the code and a custom automation cheat sheet created by Frank.
Extracting Tables from Websites with Pandas
Use the Pandas library to extract tables from websites like Wikipedia.
The Pandas library, specifically the 'read_html' function, can be used to extract all tables from a given website URL. An example demonstrates extracting tables from a Wikipedia page listing 'The Simpsons' episodes, resulting in a list containing multiple tables.
Install Pandas using pip and import it into your script.
To use Pandas, it first needs to be installed via pip: 'pip install pandas'. If using Jupyter Notebooks, the command is '!pip install pandas'. After installation, import the library using 'import pandas as pd', where 'pd' is the conventional alias.
Pandas' read_html function returns a list of all tables found on a page.
The 'pd.read_html(url)' function takes a website URL as input and returns a Python list. Each element in this list represents a table found on the webpage. The number of tables extracted can be determined using the 'len()' function.
Access specific tables from the extracted list by their index.
Once tables are extracted into a list (e.g., 'simpsons_list'), individual tables can be accessed using their index. For instance, 'simpsons_list[1]' would retrieve the second table from the list, which in the example corresponded to Season 1 of The Simpsons.
Web Scraping CSV Files with Pandas
Pandas can read CSV files directly from a URL using read_csv.
The 'pd.read_csv(url)' function can be used to directly download and parse a CSV file from a given web address. This eliminates the need for manual downloading and is useful for accessing data stored online.
Identify CSV file links by looking for '.csv' in the URL.
When scraping data from a website that hosts CSV files, the direct URL to the file typically contains '.csv'. Right-clicking on a download link and selecting 'Copy link address' usually provides the correct URL.
Rename DataFrame columns to improve clarity using the rename method.
After loading data into a Pandas DataFrame, column names can be confusing. The '.rename()' method, used with the 'columns' parameter and a dictionary mapping old to new names, allows for renaming specific columns. 'inplace=True' updates the DataFrame directly.
Extracting Tables from PDFs with Camelot
Install Camelot and its dependencies (Tkinter, Ghostscript) to read PDF tables.
To extract tables from PDF documents, the Camelot library is used. Before installing Camelot ('pip install camelot-py'), two dependencies must be installed: Tkinter ('pip install tk') and Ghostscript ('pip install ghostscript').
Use Camelot's read_pdf function to parse tables from a specified page.
The 'camelot.read_pdf(pdf_path, page=page_number)' function extracts tables. The 'flavor' parameter can be set to 'lattice' (default) or 'stream' if the default parsing fails. The output is a list of 'Table' objects.
Export extracted PDF tables to various formats like CSV.
Each 'Table' object extracted by Camelot has an '.export()' method. This method can save the table to different formats, such as CSV, by specifying the output filename and format parameter (e.g., 'tables[0].export('foo.csv', format='csv')').
HTML Basics for Web Scraping
Understand HTML tags, attributes, and elements for effective web scraping.
HTML (HyperText Markup Language) is the standard language for creating web pages. Key components include tags (e.g., '<p>', '<h1>'), which define structure and formatting, attributes (e.g., 'class', 'id'), which customize tags, and entire elements comprising tags, attributes, and content.
Identify essential HTML tags for web scraping like head, body, header, article, p, h1-h3, div, nav, li, and a.
Key HTML tags used in web scraping include: 'head' (metadata), 'body' (main content), 'header' (introductory content), 'article' (blog posts, entries), 'p' (paragraphs), 'h1'-'h3' (headings), 'div' (generic container), 'nav' (navigation), 'li' (list items), and 'a' (anchor/links, often with 'href' attribute).
Recognize tags for structuring tabular data (table, tr, td) and interactive elements (button).
For tabular data, '<table>', '<tr>' (table row), and '<td>' (table data) are crucial. The 'button' tag is used for clickable elements, often within forms.
Understand iframe tags for embedded content, which can complicate scraping.
The '<iframe>' tag embeds another HTML document within the current one. This can sometimes require switching context between frames during the scraping process.
HTML structure forms a tree where elements are nodes with parent-child relationships.
Web pages are structured as a Document Object Model (DOM) tree. Each HTML tag and its content form a 'node'. Nodes have parent-child and sibling relationships, which are fundamental for navigating and selecting elements using tools like XPath.
Attributes like 'class' and 'id' are critical for targeting specific elements during scraping.
Attributes, particularly 'class' and 'id', provide unique identifiers or categories for HTML elements. These are essential for precisely selecting the desired data points when scraping a webpage.
XPath for Element Selection
XPath is a query language for selecting nodes in XML/HTML documents.
XPath (XML Path Language) is used to navigate and select elements (nodes) within structured documents like HTML. It provides a powerful way to query and extract specific data from web pages.
Use double slash (//) to select nodes at any level of the document tree.
The '//' syntax in XPath allows selection of matching nodes anywhere within the HTML document, regardless of their depth or parentage. For example, '//h1' selects all h1 elements.
Select specific elements by index using square brackets (e.g., //h1[1]).
To select a specific element when multiple exist, you can use square brackets with a number indicating its position (1-based index). For instance, '//h1[1]' selects the first h1 element found.
Target elements by attribute using syntax like //@attribute='value'.
Elements can be selected based on their attributes. The syntax '@attribute_name='attribute_value'' (e.g., '//@class='title'') allows precise targeting. This is commonly used for classes and IDs.
Utilize functions like 'contains()' and 'startswith()' for flexible text matching within attributes.
XPath functions like 'contains(@attribute, 'substring')' or 'startswith(@attribute, 'prefix')' provide advanced options for matching attribute values that are not exact but follow a pattern.
Use logical operators 'or' and 'and' within square brackets for combined conditions.
XPath allows combining multiple conditions within the selection brackets using logical operators like 'or' and 'and', enabling more complex queries.
Extract text content using '/text()' after locating the element.
Once an element is selected, its text content can be retrieved by appending '/text()' to the XPath expression.
Special XPath Characters and Selenium Setup
Single slash (/) selects immediate children, while double slash (//) selects any descendant.
The single slash '/' selects only direct children of the current node, whereas the double slash '//' selects nodes at any level of depth within the document.
Dot (.) refers to the current node, and double dots (..) refer to the parent node.
The '.' character in XPath represents the current context node, while '..' navigates up to the parent node, useful for finding elements relative to their ancestors.
Asterisk (*) acts as a wildcard, selecting all elements or attributes regardless of name.
The asterisk '*' is a wildcard that matches any element or attribute name at the current level or descendant level, depending on preceding slashes (e.g., '//article/*' selects all children of any article element).
Selenium requires ChromeDriver, matching your Chrome browser version.
To use Selenium with Chrome, you need to download ChromeDriver. It's crucial that the ChromeDriver version matches your installed Google Chrome browser version. The path to the downloaded ChromeDriver executable must be specified.
Install Selenium using pip: 'pip install selenium'.
The Selenium library can be installed using pip in your terminal or IDE: 'pip install selenium'.
Initialize WebDriver using Selenium 4 requires specifying ChromeService.
In Selenium 4, initializing the Chrome WebDriver involves creating a 'Service' object with the executable path of ChromeDriver and then passing this service object to the WebDriver. 'webdriver.Chrome(service=Service(executable_path=path))'.
Web Browser Automation with Selenium
Use Selenium's WebDriver to interact with web browsers programmatically.
Selenium's WebDriver allows you to control a web browser through Python code. This enables automated tasks like navigating pages, clicking buttons, and extracting data.
Identify HTML elements using XPath, CSS selectors, ID, or class names.
Selenium provides methods like 'find_element()' and 'find_elements()' which accept locators (e.g., By.XPATH, By.ID, By.CLASS_NAME) to identify specific elements on a web page.
Use find_elements() (plural) to retrieve a list of all matching elements.
Employing 'find_elements()' instead of 'find_element()' is crucial when multiple instances of an element match the given locator. It returns a list of all found WebElements.
Iterate through found elements using a for loop for processing.
Once a list of elements is obtained using 'find_elements()', a for loop can be used to process each element individually, extracting specific data like titles, subtitles, or links.
Extract text content from an element using the '.text' attribute.
The '.text' attribute of a WebElement object returns the visible text content within that element.
Retrieve attribute values (like href) using the '.get_attribute('attribute_name')' method.
To get the value of an attribute (e.g., 'href' for links), use the '.get_attribute()' method on the WebElement, passing the attribute name as a string argument.
Store extracted data by appending it to Python lists.
Collected data points (titles, subtitles, links) should be appended to corresponding Python lists during the iteration process.
Convert lists of extracted data into a Pandas DataFrame for structured output.
A Pandas DataFrame can be created from the lists of extracted data using 'pd.DataFrame({'column_name': list_name})'. This organizes the data into rows and columns.
Export the DataFrame to a CSV file using the '.to_csv()' method.
The DataFrame can be easily saved to a CSV file using the '.to_csv('filename.csv')' method. This provides a convenient way to store and share the scraped data.
Close the browser session using 'driver.quit()' after scraping.
It is essential to close the browser instance opened by Selenium using 'driver.quit()' to release resources and terminate the session cleanly.
Execute Selenium scripts in headless mode by configuring Chrome options.
To run browser automation without a visible UI, configure Chrome options by importing 'Options' from 'selenium.webdriver.chrome.options', creating an 'options' object, setting 'options.headless = True', and passing this object to the WebDriver.
Schedule Python scripts to run automatically at specific times using OS tools.
Python scripts can be scheduled to execute at desired intervals (e.g., daily) using operating system task schedulers (like Task Scheduler on Windows or cron on Linux/macOS). This requires converting the .py file to an executable.
Advanced Automation: Headless Mode & Scheduling
Configure Chrome options to enable headless execution for browser automation.
To run Selenium scripts without opening a visible browser window, instantiate 'Options' from 'selenium.webdriver.chrome.options', set its 'headless' attribute to 'True', and pass this options object when initializing the WebDriver.
Rename output CSV files dynamically using date and time for tracking.
To avoid overwriting data and to easily identify the execution date, customize the output filename by incorporating date and time information using the 'datetime' module and '.strftime()' formatting.
Prepare Python scripts for execution by converting them to standalone executables.
Before scheduling, Python scripts (.py files) often need to be converted into standalone executable files (.exe on Windows) using tools like PyInstaller. This ensures the script can run independently of a Python installation.
Use 'sys' and 'os' modules to manage file paths correctly for executables.
When running as an executable, file paths can behave differently. Using `sys.executable` and `os.path.dirname` helps determine the correct directory for saving output files relative to the executable's location.
Ask a Question
*Uses 1 Wisdom coin from your coin balance











