-
Notifications
You must be signed in to change notification settings - Fork 1
/
scrapeWPW.py
178 lines (147 loc) · 5.2 KB
/
scrapeWPW.py
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
'''
scrapeWPW.py
By Kevin McElwee
A series of functions that ultimately create a single CSV, allData_raw.csv,
which contains all the data from WhoPaysWriters.com.
'''
import pandas as pd
import os
from bs4 import BeautifulSoup
from selenium import webdriver
import csv
import time
def getAllPublications():
''' retrieve list of publications from WPW homepage, create csv'''
url = 'http://whopayswriters.com/#/results'
browser = webdriver.Chrome()
browser.get(url)
time.sleep(1.5) # wait for page to load
html = browser.page_source
soup = BeautifulSoup(html, 'html.parser')
mainContent = soup.find('div', {'class': 'main-content'})
sideList = mainContent.find_all('li')
pubAndLink = [(l.text, l.find('a')['href'], 0) for l in sideList]
with open('publications.csv', 'w') as f:
csv_out = csv.writer(f)
csv_out.writerow(['pub', 'link', 'madeCSV'])
for r in pubAndLink:
csv_out.writerow(r)
def scrapePage(publication, browser):
'''Scrape all data given publication page, return a list of rows dictionaries'''
html = browser.page_source
soup = BeautifulSoup(html, 'html.parser')
listOfRows = []
dataByYear = soup.find_all('div', {'ng-repeat':'year in orderedYears'})
for m in dataByYear:
year = m.h3.text
submissions = m.find_all('div', {'ng-repeat': 'interaction in interactionsByYear[year]'})
for s in submissions:
r = {}
r['publication'] = publication
r['year'] = year
dollaz = s.find('div', {'class': 'dollaz'})
rateAndKind = dollaz.find_all('span')
if len(rateAndKind) != 0:
r['dollar'] = rateAndKind[0].text
r['flatRate'] = 'flat' in rateAndKind[1].text
else:
r['dollar'] = None
r['flatRate'] = None
temp = s.find('div', {'class': 'payment'}).span.text
r['paidYet'] = None if temp == ' ' else temp
r['paymentDifficulty'] = s.find('div', {'class': 'payment'}).i['class'][-1]
comment = s.find('section', {'ng-if': 'interaction.comment'})
r['comment'] = comment if comment is None else comment.text
mainStuff = s.find('div', {'class': 'main item'}).find('section')
wordCountAndKind = mainStuff.find('p', {'ng-bind': 'interaction.description()'}).text
if 'word' in wordCountAndKind:
splitter = wordCountAndKind.split('-word ')
r['wordCount'] = splitter[0]
r['storyType'] = None if len(splitter) < 2 else splitter[1]
else:
r['wordCount'] = wordCountAndKind # CHANGED THIS
r['storyType'] = None
rep2 = mainStuff.find('p', {'ng-bind': 'interaction.details()'}).text
if rep2 != '':
if ';' in rep2:
r['levelOfReporting'] = rep2.split(';')[0]
r['relationship'] = rep2.split('; ')[1]
else:
r['levelOfReporting'] = rep2 # fix errors in notebook
else:
r['levelOfReporting'] = None
r['relationship'] = None
icons = s.find('div', {'class': 'main item'}).find('div', {'class': 'icons'})
all_is = icons.find_all('i')
for i in all_is:
q = i['data-title']
if 'Contract' in q:
r['contract'] = q
if 'Rights' in q:
r['rights'] = q
# multiple platforms allowed
# let's only make one platform column
# let's say print trumps digital trumps other
if 'Platform' in q:
if 'print' in q:
r['platform'] = q
elif 'digital' in q:
r['platform'] = q
elif 'other' in q:
r['platform'] = q
listOfRows.append(r)
return listOfRows
def create_Publication_CSVs(sleepSeconds=0.8):
'''call scrapePage() to create a csv for each publication'''
df = pd.read_csv('publications.csv')
browser = webdriver.Chrome()
for i, row in df.iterrows():
if not bool(row['madeCSV']):
publication = row['pub']
print(str(i) + ' ' + publication)
url = 'http://whopayswriters.com/' + row['link']
browser.get(url)
time.sleep(sleepSeconds) # wait for full page to load
info = scrapePage(publication, browser)
df_temp = pd.DataFrame(info)
df_temp.to_csv('data/' + (row['link'].split('/')[-1]) + '.csv', index=False)
# change the publications.csv so we don't scrape this data again
df.at[i, 'madeCSV'] = 1
df.to_csv('publications.csv', index=False)
def combine_csvs():
''' Combine each publication's csvs into one large csv '''
errorFiles = []
df = pd.DataFrame()
for file in os.listdir('data'):
if file.endswith('.csv'):
try:
df = df.append(pd.read_csv('data/' + file), ignore_index=True, sort=False)
except:
errorFiles.append(file)
file
df.to_csv('allData_raw.csv', index=False)
return errorFiles
def doubleCheckErrors(errorFiles1, sleepSeconds=.5):
print('Errors on the first scrape attempt:')
for e in errorFiles1:
print(e, end=', ')
print('\n' + '#'*50)
print('\nTesting again with extra time: {} seconds'.format(sleepSeconds))
errorLinks = ['#/publication/' + e[:-4] for e in errorFiles1]
df = pd.read_csv('publications.csv')
df.loc[df['link'].isin(errorLinks), 'madeCSV'] = 0
df.to_csv('publications.csv', index=False)
create_Publication_CSVs(sleepSeconds=sleepSeconds)
errorFiles2 = combine_csvs()
fixes = [e for e in errorFiles1 if e not in errorFiles2]
print('\n' + '#'*50)
print('Error Files corrected:', len(fixes))
for f in fixes:
print(f)
def main():
# getAllPublications()
# create_Publication_CSVs()
errorFiles = combine_csvs()
doubleCheckErrors(errorFiles)
if __name__ == '__main__':
main()