For this project, I am scraping data from a database and attempting to export this data to a spreadsheet for further analysis.
While my code seems mostly to work well, when it comes to the last bit--exporting to CSV--I am having no luck. This question has been asked a few times, however it seems the answers were geared towards different approaches, and I didn't have any luck adapting their answers.
My code is below:
from bs4 import BeautifulSoup
import requests
import re
url1 = "http://www.elections.ca/WPAPPS/WPR/EN/NC?province=-1&distyear=2013&district=-1&party=-1&pageno="
url2 = "&totalpages=55&totalcount=1368&secondaryaction=prev25"
date1 = []
date2 = []
date3 = []
party=[]
riding=[]
candidate=[]
winning=[]
number=[]
for i in range(1, 56):
r = requests.get(url1 + str(i) + url2)
data = r.text
cat = BeautifulSoup(data)
links = []
for link in cat.find_all('a', href=re.compile('selectedid=')):
links.append("http://www.elections.ca" + link.get('href'))
for link in links:
r = requests.get(link)
data = r.text
cat = BeautifulSoup(data)
date1.append(cat.find_all('span')[2].contents)
date2.append(cat.find_all('span')[3].contents)
date3.append(cat.find_all('span')[5].contents)
party.append(re.sub("[\n\r/]", "", cat.find("legend").contents[2]).strip())
riding.append(re.sub("[\n\r/]", "", cat.find_all('div', class_="group")[2].contents[2]).strip())
cs= cat.find_all("table")[0].find_all("td", headers="name/1")
elected=[]
for c in cs:
elected.append(c.contents[0].strip())
number.append(len(elected))
candidate.append(elected)
winning.append(cs[0].contents[0].strip())
import csv
file = ""
for i in range(0,len(date1)):
file = [file,date1[i],date2[i],date3[i],party[i],riding[i],"\n"]
with open ('filename.csv','rb') as file:
writer=csv.writer(file)
for row in file:
writer.writerow(row)
Really--any tips would be GREATLY appreciated. Thanks a lot.
*PART 2: Another question: I previously thought that finding the winning candidate in the table could be simplified by just always selecting the first name that appears in the table, as I thought the "winners" always appeared first. However, this is not the case. Whether or not a candidate was elected is stored in the form of a picture in the first column. How would I scrape this and store it in a spreadsheet? It's located under < td headers > as:
< img src="/WPAPPS/WPR/Content/Images/selected_box.gif" alt="contestant won this nomination contest" >
I had an idea for attempting some sort of Boolean sorting measure, but I am unsure of how to implement. Thanks a lot.* UPDATE: This question is now a separate post here.
open('filename.csv','rb'), you should open the file for writing asopen('filename.csv','wb').