Web Scraper & Data Extraction with Python | Upwork Series #1
Tags: python, webdev, database, tutorial
Published: 2020-01-02 16:00:08

This post cross-published with [OnePublish](https://www.onepubli.sh)

<p>Welcome to the first post of Upwork Series. In this series, we are going to work on real-world applications.</p>

<p>What is the main difference between this channel from others? I am trying to show you real-world applications instead of just simple tutorials. Complex projects will increase your algorithmic thinking and problem-solving skills. In these videos I didn't record my voice, the reason is, I already explained the project in my blog post so I am just showing the procedure of the project step by step. But if you want explanation in videos, let me know in comments.</p>

<p>Alright! Let's start!</p>

<h3>Web Scraper & Data Extraction</h3>
<p>Our task is to create web crawler which will scrape data daily from the  report pages of transportation company.</p>
<p><a href="https://www.upwork.com/jobs/~014313c9236c58d361">Click here to see description of project</a></p>
<img src="https://thepracticaldev.s3.amazonaws.com/i/mvsy8twz98egdcquu2kj.png" alt="Reverse Python" />

<h4>Step 1: Understanding the task</h4>
<p>First, it is important to understand the task clearly. They want from us to scrape data then save it in CSV file where each attribute listed above is its own separate column.</p>

<p>We are going to crawl the following information:</p>

<ul>
<li> Date ("The information below reflects the content of the FMCSA management information systems as of {Date}")</li>
<li> Operating Status</li>
<li> Legal Name</li>
<li> DBA Name</li>
<li> Physical Address</li>
<li> Mailing Address</li>
<li> USDOT Number</li>
<li> Power Units</li>
<li> Drivers </li>
</ul>

<blockquote>We can provide an initial set of 100 DOT numbers to make sure the information above can be scraped easily, from there we can provide all DOT numbers we would like to scrape on a daily basis. </blockquote>

<p>Report pages can be accessed by dots or with other name IDs. Each page has its own id (dot). So, these dots locate in Excel file. We have to read this file and extract dots from there then pass it into URL to access the report page.</p>

<h4>Step 2: Creating our environment and installing dependencies</h4>
<p>Now, we know what client wants from us, so let's create our virtual environment then inspect elements that we are going to crawl.</p>

<p>To create virtualenv run the following command in your terminal:</p>

```
virtualenv env
```

<p>then install <b>BeautifulSoup</b> which is a Python package for parsing HTML and XML documents and <b>xlrd</b> which is a library for reading data and formatting information from Excel files:</p>

```
pip install beautifulsoup4 xlrd
```

<h4>Step 3: Crawling Data</h4>
<p>Alright Devs! Let's start with opening the example url from project description so can see the fields.</p>

<a href="https://safer.fmcsa.dot.gov/query.asp?searchtype=ANY&query_type=queryCarrierSnapshot&query_param=USDOT&query_string=3049931">Click to see Example URL</a>

<p>The page should look like this:</p>

<img src="https://thepracticaldev.s3.amazonaws.com/i/evnnxhdvp05m7x9h9n6u.png" alt="Reverse Python" />

<p>Our first target is to find - Date ("The information below reflects the content of the FMCSA management information systems as of {Date}")</p>

<blockquote>The information below reflects the content of the FMCSA management information systems as of 01/01/2020. </blockquote>

<p>The truth is we can't crawl this element by specific class name or id. Unfortunately, this report pages messed up.</p>

<p>But we can see that this element is in <b>bold</b> format. There are also many elements locate with the bold format. However, we can crawl all of them as text and use <b>RegEx</b> to extract the data we need.</p>

<p>A regular expression (RegEx) is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern.</p>

<p>The date locates between <b>The information below reflects the content of the FMCSA management information systems as of</b> and <b>.(dot)</b>. So , to find the date regex will look between these strings.</p>

```python
import re # regex
import urllib.request
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup

def crawl_data(url):
    req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    html = urlopen(req).read()
    bs = BeautifulSoup(html, 'html.parser')
    # Find all bold texts
    bold_texts = bs.find_all('b')
    for b in bold_texts:
        try:
            # look between these strings
            date = re.search('The information below reflects the content of the FMCSA management information systems as of(.*).', b.get_text(strip=True, separator='  ')).group(1).strip()   
            # If regex finds multiple dots, extract string before first dot                    
            if len(date) > 11:
                date = date.split(".",1)[0]
            print(date)
        except AttributeError:
            pass
```

<p>Well if you run the program you will see it's printing the date.</p>

<p>Let me quickly show you how regex works, because I feel some of you trying to understand.</p>

<p>Consider the following code:</p>
```python
import re

# We need to extarct "coderasha" from the string
data = "Hello my name is coderasha."
name = re.search('Hello my name is (.*).', data)
print(name)

# Output: <_sre.SRE_Match object; span=(0, 27), match='Hello my name is coderasha.'>
```
<p>As you see match is found but its printed like object. <b>group(1)</b> capture the text matched by the regex inside them into a numbered group that can be reused with a numbered backreference</p>

```python
import re

# We need to extarct "coderasha" from the string
data = "Hello my name is coderasha."
name = re.search('Hello my name is (.*).', data).group(1)
print(name)

# Output: coderasha
```
<p>So, I am applying the same logic to find the date inside strings that crawled.</p>

<p> The next step is, to find a table and continue to crawl other fields. Luckily, the table locates between <b>center</b> tags. However, we have to find data again using RegEx because table elements have no any special attribute.</p>

```python
# Get all texts inside table
 information = bs.find('center').get_text(strip=True, separator='  ')
# Find fields using RegEx
    operating = re.search('Operating Status:(.*)Out', information).group(1).strip()
    legal_name = re.search('Legal Name:(.*)DBA', information).group(1).strip()
    physical_address = re.search('Physical Address:(.*)Phone', information).group(1).strip()
    mailing_address = re.search('Mailing Address:(.*)USDOT', information).group(1).strip()
    usdot_address = re.search('USDOT Number:(.*)State Carrier ID Number', information).group(1).strip()
    power_units = re.search('Power Units:(.*)Drivers', information).group(1).strip()
    drivers = re.search('Drivers:(.*)MCS-150 Form Date', information).group(1).strip()
```
<h4>Step 4: Write data in CSV</h4>
<p>Once data crawled, it is time to create new csv file and write data into it. I prefer to create another function which will handle this action.</p>

```python
import csv

def write_csv(date, operating, legal_name, physical_address, mailing_address, usdot_address, power_units, drivers):
    with open(usdot_address + '.csv', mode='w', newline='', encoding="utf-8") as csv_file:
            fieldnames = ['Date', 'Operating Status', 'Legal_Name', 'Physical Address', 'Mailing Address', 'Power Units', 'Drivers']
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerow({ 'Date':date, 'Operating Status': operating, 'Legal_Name': legal_name, 'Physical Address':physical_address, 'Mailing Address': mailing_address, 'Power Units':power_units, 'Drivers':drivers })               
```

<p>CSV name must be unique, so I named it with <b>usdot_address</b> or with other name ID of report page from crawled data</p>

<h4>Step 5: Read excel file to crawl data for each dot</h4>

<p>The final step is to read excel file and pass these dots end of the URL to access the pages. We can use <b>xlrd</b> to read excel file</p>

```python
import xlrd

dots = []

def read_excel_file():
    loc = ("dots.xls") 
    wb = xlrd.open_workbook(loc) 
    sheet = wb.sheet_by_index(0) 
    sheet.cell_value(0, 0)
    # First five dot in excel 
    for i in range(1,5): 
        # Convert floats to string and clean from .0
        dot = str(sheet.cell_value(i, 0)).replace('.0', '')
        dots.append(dot)
```
<p>xlrd reads numbers as float so the best solution is to covert them to strings and use <b>replace()</b> method to remove .0 end of the string.</p>

<p>and pass these dots into url:</p>

```python
for dot in dots:
    crawl_data('https://safer.fmcsa.dot.gov/query.asp?searchtype=ANY&query_type=queryCarrierSnapshot&query_param=USDOT&query_string=' + dot)     
    # Sleep 5 seconds to avoid any errors     
    time.sleep(5)
```

<p>Here is the Full Code:</p>

```python
import re
import csv
import urllib.request
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
import xlrd 
import time

dots = []

def read_excel_file():
    loc = ("dots.xls") 
    wb = xlrd.open_workbook(loc) 
    sheet = wb.sheet_by_index(0) 
    sheet.cell_value(0, 0) 
    for i in range(1,5): 
        dot = str(sheet.cell_value(i, 0)).replace('.0', '')
        dots.append(dot)


def crawl_data(url):
    req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    html = urlopen(req).read()
    bs = BeautifulSoup(html, 'html.parser')
    bold_texts = bs.find_all('b')
    for b in bold_texts:
        try:
            date = re.search('The information below reflects the content of the FMCSA management information systems as of(.*).', b.get_text(strip=True, separator='  ')).group(1).strip()
            if len(date) > 11:
                date = date.split(".",1)[0]
            print(date)
        except AttributeError:
            pass

    information = bs.find('center').get_text(strip=True, separator='  ')

    operating = re.search('Operating Status:(.*)Out', information).group(1).strip()
    legal_name = re.search('Legal Name:(.*)DBA', information).group(1).strip()
    physical_address = re.search('Physical Address:(.*)Phone', information).group(1).strip()
    mailing_address = re.search('Mailing Address:(.*)USDOT', information).group(1).strip()
    usdot_address = re.search('USDOT Number:(.*)State Carrier ID Number', information).group(1).strip()
    power_units = re.search('Power Units:(.*)Drivers', information).group(1).strip()
    drivers = re.search('Drivers:(.*)MCS-150 Form Date', information).group(1).strip()
    
    write_csv(date, operating, legal_name, physical_address, mailing_address, usdot_address, power_units, drivers)

def write_csv(date, operating, legal_name, physical_address, mailing_address, usdot_address, power_units, drivers):
    with open(usdot_address + '.csv', mode='w', newline='', encoding="utf-8") as csv_file:
            fieldnames = ['Date', 'Operating Status', 'Legal_Name', 'Physical Address', 'Mailing Address', 'Power Units', 'Drivers']
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerow({ 'Date':date, 'Operating Status': operating, 'Legal_Name': legal_name, 'Physical Address':physical_address, 'Mailing Address': mailing_address, 'Power Units':power_units, 'Drivers':drivers })                


read_excel_file()
print(dots)
for dot in dots:
    crawl_data('https://safer.fmcsa.dot.gov/query.asp?searchtype=ANY&query_type=queryCarrierSnapshot&query_param=USDOT&query_string=' + dot)
    time.sleep(5)
```
<h4>Mission Accomplished</h4>
<p>I hope you liked the first post of new Upwork series. The job offer still open so if want you can send proposal to client using this code.
Please take look <a href="https://reversepython.net"> Reverse Python </a> for more articles like this and subscribe to <a href="https://www.youtube.com/channel/UCEwYRHE5ZAOMfUaIpCQvjEQ?view_as=subscriber">YouTube Channel - Reverse Python</a> for amazing content.
</p>
<p>See you soon Devs! Stay Connected!</p>