I've written a simple web scraper in Python. As it is my first venture in Python, I'd like to ask for a code review from more experienced coders. All input is welcome.
A little bit of background:
I'm a huge fan of video games. In Japan, there is a company called Media Create which tracks all sales of games and consoles and releases them weekly (in Japanese language). Another site (www.gematsu.com) translates those charts and releases them weekly on their website. My script fetches the data and saves it to a text file.
The script should run as-is, but it is dependent on a text file of the previous week existing in script-location/data.
The name of the script needs to be something like media-create-sales-11-26-18-12-2-18.txt
(replacing the start and end dates with any dates other than the dates of the most recently released data).
I am not affiliated with Media Create or Gematsu and this script serves no commercial purpose.
import requests
from bs4 import BeautifulSoup
import datetime
import glob
import os
def getLatestFilename():
list_of_files = glob.glob('data/*')
latest_file = max(list_of_files, key=os.path.getctime)
return latest_file
def parseUrl(dateString):
dateString = dateString.split('-')
lastdateString = str("-".join(dateString[6:9])).split('.')[0]
lastdate_object = datetime.datetime.strptime(lastdateString, "%m-%d-%y")
current_startdatetime_object = lastdate_object + datetime.timedelta(days=1)
current_enddatetime_object = lastdate_object + datetime.timedelta(days=7)
cur_startDateString = current_startdatetime_object.strftime("%m-%d-%y").lstrip("0").replace("0", "")
cur_endDateString = current_enddatetime_object.strftime("%m-%d-%y").lstrip("0").replace("0", "")
return (cur_startDateString + '-' + cur_endDateString)
def getUrl(filename):
curIntervalString = parseUrl(filename)
now = datetime.datetime.now()
url = list()
url.append("https://gematsu.com/")
url.append(str(now.year))
url.append('/')
url.append(str(now.month))
url.append('/')
url.append('media-create-sales-')
url.append(curIntervalString)
return url
def fetchContentForUrl(url):
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
outputfile = open("data/media" + url.split('media')[1] + ".txt", "w")
outputfile.write(url + '\n' + '\n')
content = soup.find(class_='entry')
gameCharts = content.findNext('ol')
gameEntries = gameCharts.find_all('li')
for idx,entry in enumerate(gameEntries,start=1):
outputfile.write(str(idx) + "." + entry.get_text() + "\n")
print ('\n')
consoleCharts = gameCharts.find_next_sibling("ol")
consoleEntries = consoleCharts.find_all('li')
for entry in consoleEntries:
outputfile.write(entry.get_text() + "\n")
def main():
latestFilename = getLatestFilename()
print (latestFilename)
url = ''.join(getUrl(latestFilename))
print (url)
fetchContentForUrl(url)
if __name__ == '__main__':
main()