chuppy

Python is fun

This is an application of the Beautiful Soup library in Python. I used it to get and store a number of posts from a well known portuguese message board. All the posts would be separated in content, user, section, url and an unique identifier.

Python is somewhat weird to use for someone like me who is more experienced in C# and Java but i can see why it has such a following for developers still learning.

Main program

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# Importar bibliotecas

import sqlite3
from sqlite3 import Error

import datetime

import requests
from bs4 import BeautifulSoup


def createWordList(line):
    wordList2 = []
    wordList1 = line.split ()
    for word in wordList1:
        cleanWord = ""
        for char in word:
            if char in '!,.?":;0123456789':
                char = ""
            cleanWord += char
        wordList2.append ( cleanWord )
    return wordList2


def create_connection(db_file):
    """ create a database connection to the SQLite database
        specified by db_file
    :param db_file: database file
    :return: Connection object or None
    """
    conn = None
    try:
        conn = sqlite3.connect ( db_file )
    except Error as e:
        print ( e )

    return conn


# ---- update this with cookie and headers
cookies = {
}

headers = {
}

database = r".\chuppy2.db"


def insert_row(conn , project , post_date , post_number , post_user , post_content , post_url):
    """
    Create a new project into the projects table
    :param conn:
    :param project:
    :param post_date:
    :param post_number:
    :param post_user:
    :param post_content:
    :return: project id
    """
    sql = ''' INSERT INTO tbl_posts(post_date,post_number,post_user,post_content,post_project,post_url)
              VALUES(?,?,?,?,?,?) '''
    cur = conn.cursor ()

    data_tuple = (post_date , post_number , post_user , post_content , project , post_url)
    cur.execute ( sql , data_tuple )
    return cur.lastrowid


def insert_row_thread(conn , project , url):
    """
    Create a new project into the projects table
    :param conn:
    :param project:
    :param post_date:
    :param post_number:
    :param post_user:
    :param post_content:
    :return: project id
    """
    sql = ''' INSERT INTO tbl_urls(thread_url,thread_title,checked)
              VALUES(?,?,?) '''
    cur = conn.cursor ()

    data_tuple = (url , project , 0)
    cur.execute ( sql , data_tuple )
    return cur.lastrowid


def print_timestamp():
    now = datetime.datetime.now ()
    print ( "Current date and time : " )
    print ( now.strftime ( "%Y-%m-%d %H:%M:%S" ) )


def insert_row_word(conn , post_project , post_id , word):
    sql = 'insert into tbl_posts_word (post_project,post_num,word) VALUES (?,?,?)'
    cur = conn.cursor ()
    data_tuple = (post_project , post_id , word)
    cur.execute ( sql , data_tuple )
    return cur.lastrowid

def return_thread_url(conn):
    sql='select thread_url, thread_title, uniqid from tbl_urls where checked=0 ORDER BY RANDOM() LIMIT 1'
    cur = conn.cursor()
    cur.execute(sql)

    rows = cur.fetchall()

    for row in rows:
        return row

def update_thread_url(conn,uniqid):
    sql="update tbl_urls set checked=1 where uniqid="+str(uniqId)
    cur= conn.cursor()
    cur.execute(sql)

def parse_pages(threadUrls):
    for threadUrl in threadUrls:
        statusCode = 200
        pageCount = 1
        maxPageCount = 1
        print ( '{}\n'.format ( siteUrl + threadUrl['href'] ) , end = "" , flush = True )

        while statusCode == 200 and pageCount <= maxPageCount:
            url = siteUrl + threadUrl['href'] + '/page' + str ( pageCount )

            pageContent = requests.get ( url , headers = headers , cookies = cookies )
            statusCode = pageContent.status_code

            pageCount += 1
            pageSoup = BeautifulSoup ( pageContent.content , 'html.parser' )

            # print ( pageSoup.prettify() )
            users = []
            for usr in pageContent:
                users.append ( pageSoup.find ( "strong" ) )

            dates = pageSoup.find_all ( "span" , class_ = "date" )
            times = pageSoup.find_all ( "span" , class_ = "time" )
            postnums = pageSoup.find_all ( "a" , class_ = "postcounter" )
            messages = pageSoup.find_all ( "span" , class_ = "messagetext" )
            postUrls = pageSoup.find_all ( "a" , class_ = "postcounter" )
            for y in range ( len ( messages ) ):
                insert_row ( conn , threadUrl.contents[0] , dates[y].text , postnums[y].text , users[y].text ,
                             messages[y].text , postUrls[y].text )
        else:
            print ( "no more pages" )

def return_num_posts(endPText):
    startIndex=endPText.text.find("of")
    endIndex= len ( endPText.text )
    numP=endPText.text[startIndex+3:endIndex-5]
    return numP

# create a database connection
conn = create_connection ( database )
with conn:
    maxIter=500
    for y in range( maxIter):
        print("page {}".format(y))
        print_timestamp ()
        maxPageNum = 6500
        urlData=return_thread_url(conn)
        startPage = urlData[0]+"/page"
        project=urlData[1]
        uniqId=urlData[2]
        # ---- update this with main url
        siteUrl = ""
        for x in range ( maxPageNum ):

            url = startPage + str ( x )
            print ( url )
            response = requests.get ( url , headers = headers , cookies = cookies )

            pageContent = requests.get ( url , headers = headers , cookies = cookies )
            statusCode = pageContent.status_code

            pageSoup = BeautifulSoup ( pageContent.content , 'html.parser' )
            if x == 1:
                endPage=pageSoup.find("div", class_="postpagestats")
                maxPageNum=int(return_num_posts(endPage))/20

            if x>maxPageNum:
                print_timestamp ()
                print ( "Max page Reached" )
                print ("updating id "+str(uniqId))
                update_thread_url ( conn , str(uniqId) )
                break

            users = pageSoup.find_all ( "a" , class_ = "username" )
            dates = pageSoup.find_all ( "span" , class_ = "date" )
            times = pageSoup.find_all ( "span" , class_ = "time" )
            postnums = pageSoup.find_all ( "a" , class_ = "postcounter" )
            messages = pageSoup.find_all ( "span" , class_ = "messagetext" )
            postUrls = pageSoup.find_all ( "a" , class_ = "postcounter" )
            for y in range ( len ( messages ) ):
                insert_row ( conn , project , dates[y].text , postnums[y].text , users[y].text ,
                             messages[y].text , url + postUrls[y]['href'] )
            print ( 'página {} - {:%}%\n'.format ( x , x / maxPageNum ) , end = "" , flush = True )
        else:

            print_timestamp ()
            print ( "no more pages" )

Database structure

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
CREATE TABLE "tbl_posts" (
	"uniqid"	INTEGER,
	"post_date"	TEXT,
	"post_number"	TEXT,
	"post_user"	TEXT,
	"post_content"	TEXT,
	"post_project"	TEXT,
	"post_url"	TEXT,
	PRIMARY KEY("uniqid" AUTOINCREMENT)
)

CREATE TABLE "tbl_urls" (
	"uniqid"	INTEGER,
	"thread_url"	TEXT,
	"checked"	NUMERIC,
	"thread_title"	TEXT,
	PRIMARY KEY("uniqid" AUTOINCREMENT)
)
Built with Hugo
Theme Stack designed by Jimmy