changedotorgscraper 0.0.9__tar.gz → 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ChangeDotOrgScraper-0.1.0/ChangeDotOrgScraper/ChangeDotOrgScraper.py +423 -0
- {changedotorgscraper-0.0.9 → ChangeDotOrgScraper-0.1.0}/ChangeDotOrgScraper.egg-info/PKG-INFO +26 -20
- {changedotorgscraper-0.0.9 → ChangeDotOrgScraper-0.1.0}/ChangeDotOrgScraper.egg-info/requires.txt +4 -2
- {changedotorgscraper-0.0.9 → ChangeDotOrgScraper-0.1.0}/PKG-INFO +26 -20
- {changedotorgscraper-0.0.9 → ChangeDotOrgScraper-0.1.0}/setup.py +26 -7
- changedotorgscraper-0.0.9/ChangeDotOrgScraper/ChangeDotOrgScraper.py +0 -185
- {changedotorgscraper-0.0.9 → ChangeDotOrgScraper-0.1.0}/ChangeDotOrgScraper/__init__.py +0 -0
- {changedotorgscraper-0.0.9 → ChangeDotOrgScraper-0.1.0}/ChangeDotOrgScraper.egg-info/SOURCES.txt +0 -0
- {changedotorgscraper-0.0.9 → ChangeDotOrgScraper-0.1.0}/ChangeDotOrgScraper.egg-info/dependency_links.txt +0 -0
- {changedotorgscraper-0.0.9 → ChangeDotOrgScraper-0.1.0}/ChangeDotOrgScraper.egg-info/top_level.txt +0 -0
- {changedotorgscraper-0.0.9 → ChangeDotOrgScraper-0.1.0}/LICENSE +0 -0
- {changedotorgscraper-0.0.9 → ChangeDotOrgScraper-0.1.0}/setup.cfg +0 -0
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
import requests
|
|
2
|
+
from bs4 import BeautifulSoup
|
|
3
|
+
import json
|
|
4
|
+
from tqdm import tqdm
|
|
5
|
+
import re
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import time
|
|
8
|
+
import requests
|
|
9
|
+
from bs4 import BeautifulSoup
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def normalize_url(url):
|
|
15
|
+
"""
|
|
16
|
+
Normalizes the search URL to ensure proper format for pagination.
|
|
17
|
+
|
|
18
|
+
Parameters:
|
|
19
|
+
- url (str): Original search URL
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
- str: Base URL ready for pagination
|
|
23
|
+
"""
|
|
24
|
+
# Remove any existing page parameter
|
|
25
|
+
url = re.sub(r'[&?]page=\d+', '', url)
|
|
26
|
+
|
|
27
|
+
# Ensure offset parameter exists
|
|
28
|
+
if 'offset=' not in url:
|
|
29
|
+
if '?' in url:
|
|
30
|
+
url = url + '&offset=0'
|
|
31
|
+
else:
|
|
32
|
+
url = url + '?offset=0'
|
|
33
|
+
else:
|
|
34
|
+
# Reset offset to 0
|
|
35
|
+
url = re.sub(r'offset=\d+', 'offset=0', url)
|
|
36
|
+
|
|
37
|
+
return url
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_page_url(base_url, page_num):
|
|
41
|
+
"""
|
|
42
|
+
Builds the URL for a specific page number.
|
|
43
|
+
|
|
44
|
+
Parameters:
|
|
45
|
+
- base_url (str): Base search URL with offset=0
|
|
46
|
+
- page_num (int): Page number (1-indexed)
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
- str: URL for the specified page
|
|
50
|
+
"""
|
|
51
|
+
# Calculate offset (10 results per page)
|
|
52
|
+
offset = (page_num - 1) * 10
|
|
53
|
+
|
|
54
|
+
# Replace offset value
|
|
55
|
+
page_url = re.sub(r'offset=\d+', f'offset={offset}', base_url)
|
|
56
|
+
|
|
57
|
+
# Add page parameter
|
|
58
|
+
if '&page=' not in page_url and '?page=' not in page_url:
|
|
59
|
+
page_url = page_url + f'&page={page_num}'
|
|
60
|
+
else:
|
|
61
|
+
page_url = re.sub(r'page=\d+', f'page={page_num}', page_url)
|
|
62
|
+
|
|
63
|
+
return page_url
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def extract_petition_from_card(card_element):
|
|
67
|
+
"""
|
|
68
|
+
Extracts petition data from a petition card element.
|
|
69
|
+
|
|
70
|
+
Parameters:
|
|
71
|
+
- card_element: BeautifulSoup element representing a petition card
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
- dict: Petition data
|
|
75
|
+
"""
|
|
76
|
+
try:
|
|
77
|
+
# Get the petition URL
|
|
78
|
+
href = card_element.get('href', '')
|
|
79
|
+
slug = href.replace('/p/', '') if href else ''
|
|
80
|
+
|
|
81
|
+
# Skip if not a petition link
|
|
82
|
+
if not href or '/p/' not in href:
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
# Try to find title - look in parent elements
|
|
86
|
+
title = ''
|
|
87
|
+
|
|
88
|
+
# Method 1: Look within the card for text content
|
|
89
|
+
title_candidates = card_element.find_all(['h2', 'h3', 'h4', 'span', 'div'])
|
|
90
|
+
for candidate in title_candidates:
|
|
91
|
+
text = candidate.get_text(strip=True)
|
|
92
|
+
if len(text) > 20 and len(text) < 500:
|
|
93
|
+
title = text
|
|
94
|
+
break
|
|
95
|
+
|
|
96
|
+
# Method 2: Get text from link itself
|
|
97
|
+
if not title:
|
|
98
|
+
title = card_element.get_text(strip=True)
|
|
99
|
+
|
|
100
|
+
# Method 3: Look at parent container
|
|
101
|
+
if not title or len(title) < 10:
|
|
102
|
+
parent = card_element.find_parent(['div', 'article', 'li'])
|
|
103
|
+
if parent:
|
|
104
|
+
# Find heading elements in parent
|
|
105
|
+
heading = parent.find(['h2', 'h3', 'h4'])
|
|
106
|
+
if heading:
|
|
107
|
+
title = heading.get_text(strip=True)
|
|
108
|
+
|
|
109
|
+
# Skip if no valid title found
|
|
110
|
+
if not title or len(title) < 5:
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
# Look for signature count in parent container
|
|
114
|
+
signatures = 0
|
|
115
|
+
parent = card_element.find_parent(['div', 'article', 'li'])
|
|
116
|
+
if parent:
|
|
117
|
+
card_text = parent.get_text()
|
|
118
|
+
sig_patterns = [
|
|
119
|
+
r'([\d,]+)\s*(?:signatures?|supporters?|signed)',
|
|
120
|
+
r'([\d,]+)\s*have signed',
|
|
121
|
+
r'signed:\s*([\d,]+)'
|
|
122
|
+
]
|
|
123
|
+
|
|
124
|
+
for pattern in sig_patterns:
|
|
125
|
+
match = re.search(pattern, card_text, re.IGNORECASE)
|
|
126
|
+
if match:
|
|
127
|
+
signatures = int(match.group(1).replace(',', ''))
|
|
128
|
+
break
|
|
129
|
+
|
|
130
|
+
# Look for creator name
|
|
131
|
+
creator = ''
|
|
132
|
+
if parent:
|
|
133
|
+
creator_patterns = [r'by\s+([A-Za-z\s\.]+)', r'started by\s+([A-Za-z\s\.]+)']
|
|
134
|
+
card_text = parent.get_text()
|
|
135
|
+
for pattern in creator_patterns:
|
|
136
|
+
match = re.search(pattern, card_text, re.IGNORECASE)
|
|
137
|
+
if match:
|
|
138
|
+
creator = match.group(1).strip()[:50] # Limit length
|
|
139
|
+
break
|
|
140
|
+
|
|
141
|
+
# Check for victory status
|
|
142
|
+
victory = False
|
|
143
|
+
if parent:
|
|
144
|
+
victory = 'victory' in parent.get_text().lower()
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
'Petition title': title[:500], # Limit title length
|
|
148
|
+
'Description': '',
|
|
149
|
+
'signature count': signatures,
|
|
150
|
+
'creator': creator,
|
|
151
|
+
'date created': '',
|
|
152
|
+
'location created': '',
|
|
153
|
+
'Victory verification status': victory,
|
|
154
|
+
'slug': slug,
|
|
155
|
+
'url': f'https://www.change.org{href}' if href.startswith('/') else href
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
except Exception:
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def scrape_with_selenium(url, max_pages=None):
|
|
163
|
+
"""
|
|
164
|
+
Scrapes Change.org search results using Selenium with proper pagination.
|
|
165
|
+
|
|
166
|
+
Parameters:
|
|
167
|
+
- url (str): Search URL from change.org
|
|
168
|
+
- max_pages (int): Maximum number of pages to scrape (None = all pages)
|
|
169
|
+
|
|
170
|
+
Returns:
|
|
171
|
+
- list[dict]: List of petitions
|
|
172
|
+
"""
|
|
173
|
+
try:
|
|
174
|
+
from selenium import webdriver
|
|
175
|
+
from selenium.webdriver.common.by import By
|
|
176
|
+
from selenium.webdriver.support.ui import WebDriverWait
|
|
177
|
+
from selenium.webdriver.support import expected_conditions as EC
|
|
178
|
+
from selenium.webdriver.chrome.options import Options
|
|
179
|
+
from selenium.webdriver.chrome.service import Service
|
|
180
|
+
from webdriver_manager.chrome import ChromeDriverManager
|
|
181
|
+
except ImportError:
|
|
182
|
+
print("Selenium not installed. Install with: pip install selenium webdriver-manager")
|
|
183
|
+
return []
|
|
184
|
+
|
|
185
|
+
# Normalize the URL
|
|
186
|
+
base_url = normalize_url(url)
|
|
187
|
+
print(f"Base URL: {base_url}")
|
|
188
|
+
|
|
189
|
+
# Setup Chrome options
|
|
190
|
+
chrome_options = Options()
|
|
191
|
+
chrome_options.add_argument("--headless")
|
|
192
|
+
chrome_options.add_argument("--no-sandbox")
|
|
193
|
+
chrome_options.add_argument("--disable-dev-shm-usage")
|
|
194
|
+
chrome_options.add_argument("--disable-gpu")
|
|
195
|
+
chrome_options.add_argument("--window-size=1920,1080")
|
|
196
|
+
chrome_options.add_argument(
|
|
197
|
+
"user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
# Initialize driver
|
|
201
|
+
try:
|
|
202
|
+
service = Service(ChromeDriverManager().install())
|
|
203
|
+
driver = webdriver.Chrome(service=service, options=chrome_options)
|
|
204
|
+
except Exception as e:
|
|
205
|
+
print(f"Error initializing Chrome driver: {e}")
|
|
206
|
+
return []
|
|
207
|
+
|
|
208
|
+
all_petitions = []
|
|
209
|
+
seen_slugs = set() # Track seen petitions to avoid duplicates
|
|
210
|
+
page_num = 1
|
|
211
|
+
consecutive_empty_pages = 0
|
|
212
|
+
max_empty_pages = 3 # Stop after 3 consecutive empty pages
|
|
213
|
+
|
|
214
|
+
try:
|
|
215
|
+
# Create progress bar (will update dynamically)
|
|
216
|
+
pbar = tqdm(desc="Scraping pages", unit="page")
|
|
217
|
+
|
|
218
|
+
while True:
|
|
219
|
+
# Check max_pages limit
|
|
220
|
+
if max_pages and page_num > max_pages:
|
|
221
|
+
print(f"\nReached max_pages limit ({max_pages})")
|
|
222
|
+
break
|
|
223
|
+
|
|
224
|
+
# Build URL for current page
|
|
225
|
+
page_url = build_page_url(base_url, page_num)
|
|
226
|
+
pbar.set_description(f"Scraping page {page_num}")
|
|
227
|
+
|
|
228
|
+
# Navigate to page
|
|
229
|
+
driver.get(page_url)
|
|
230
|
+
|
|
231
|
+
# Wait for page to load
|
|
232
|
+
try:
|
|
233
|
+
WebDriverWait(driver, 10).until(
|
|
234
|
+
EC.presence_of_element_located((By.CSS_SELECTOR, 'a[href*="/p/"]'))
|
|
235
|
+
)
|
|
236
|
+
time.sleep(2) # Additional wait for dynamic content
|
|
237
|
+
except:
|
|
238
|
+
# No petition links found - might be end of results
|
|
239
|
+
consecutive_empty_pages += 1
|
|
240
|
+
if consecutive_empty_pages >= max_empty_pages:
|
|
241
|
+
print(f"\nNo more results found after page {page_num - max_empty_pages}")
|
|
242
|
+
break
|
|
243
|
+
page_num += 1
|
|
244
|
+
pbar.update(1)
|
|
245
|
+
continue
|
|
246
|
+
|
|
247
|
+
# Parse page content
|
|
248
|
+
soup = BeautifulSoup(driver.page_source, 'html.parser')
|
|
249
|
+
|
|
250
|
+
# Find all petition links
|
|
251
|
+
petition_links = soup.find_all('a', href=re.compile(r'^/p/[^/]+/?$'))
|
|
252
|
+
|
|
253
|
+
# Extract petitions from this page
|
|
254
|
+
page_petitions = []
|
|
255
|
+
for link in petition_links:
|
|
256
|
+
petition_data = extract_petition_from_card(link)
|
|
257
|
+
if petition_data:
|
|
258
|
+
slug = petition_data.get('slug', '')
|
|
259
|
+
# Only add if not seen before
|
|
260
|
+
if slug and slug not in seen_slugs:
|
|
261
|
+
seen_slugs.add(slug)
|
|
262
|
+
page_petitions.append(petition_data)
|
|
263
|
+
|
|
264
|
+
# Check if we got any new petitions
|
|
265
|
+
if not page_petitions:
|
|
266
|
+
consecutive_empty_pages += 1
|
|
267
|
+
if consecutive_empty_pages >= max_empty_pages:
|
|
268
|
+
print(f"\nNo new results found after page {page_num - max_empty_pages + 1}")
|
|
269
|
+
break
|
|
270
|
+
else:
|
|
271
|
+
consecutive_empty_pages = 0
|
|
272
|
+
all_petitions.extend(page_petitions)
|
|
273
|
+
pbar.set_postfix({'total_petitions': len(all_petitions)})
|
|
274
|
+
|
|
275
|
+
# Check for "no results" message
|
|
276
|
+
page_text = soup.get_text().lower()
|
|
277
|
+
if 'no results' in page_text or 'no petitions found' in page_text:
|
|
278
|
+
print(f"\n'No results' message found on page {page_num}")
|
|
279
|
+
break
|
|
280
|
+
|
|
281
|
+
# Move to next page
|
|
282
|
+
page_num += 1
|
|
283
|
+
pbar.update(1)
|
|
284
|
+
|
|
285
|
+
# Small delay to be respectful to the server
|
|
286
|
+
time.sleep(1)
|
|
287
|
+
|
|
288
|
+
pbar.close()
|
|
289
|
+
|
|
290
|
+
except KeyboardInterrupt:
|
|
291
|
+
print("\nScraping interrupted by user")
|
|
292
|
+
|
|
293
|
+
except Exception as e:
|
|
294
|
+
print(f"\nError during scraping: {e}")
|
|
295
|
+
|
|
296
|
+
finally:
|
|
297
|
+
driver.quit()
|
|
298
|
+
|
|
299
|
+
print(f"\n{'='*50}")
|
|
300
|
+
print(f"Total pages taken: {page_num - 1}")
|
|
301
|
+
print(f"Total unique petitions found: {len(all_petitions)}")
|
|
302
|
+
print(f"{'='*50}")
|
|
303
|
+
print("Proceeding to extract info from each petition")
|
|
304
|
+
|
|
305
|
+
return all_petitions
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def get_petitions(url, max_pages=None):
|
|
309
|
+
"""
|
|
310
|
+
Main function to scrape Change.org petitions (Selenium only).
|
|
311
|
+
|
|
312
|
+
Parameters:
|
|
313
|
+
- url (str): Change.org search URL
|
|
314
|
+
- max_pages (int): Maximum pages to scrape (None = all pages)
|
|
315
|
+
|
|
316
|
+
Returns:
|
|
317
|
+
- list[dict]: List of petitions
|
|
318
|
+
"""
|
|
319
|
+
# print("Scraping method: selenium")
|
|
320
|
+
print(f"Max pages: {'unlimited' if max_pages is None else max_pages}")
|
|
321
|
+
print()
|
|
322
|
+
return scrape_with_selenium(url, max_pages=max_pages)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def scrape_change_org(url: str) -> dict:
|
|
328
|
+
soup = BeautifulSoup(requests.get(url).text, "lxml")
|
|
329
|
+
XXX = soup.prettify()
|
|
330
|
+
|
|
331
|
+
# brief description (meta description)
|
|
332
|
+
tag = soup.find("meta", attrs={"name": "description"})
|
|
333
|
+
brief_description = tag.get("content") if tag else None
|
|
334
|
+
|
|
335
|
+
# 1) signatureCount dict (FIRST instance)
|
|
336
|
+
needle = 'signatureCount":'
|
|
337
|
+
i = XXX.find(needle)
|
|
338
|
+
signatureCount = None
|
|
339
|
+
if i != -1:
|
|
340
|
+
start = XXX.find("{", i)
|
|
341
|
+
end = XXX.find("}", start) + 1
|
|
342
|
+
signatureCount = json.loads(XXX[start:end])
|
|
343
|
+
|
|
344
|
+
# 2) petition owner displayName
|
|
345
|
+
m = re.search(r'"petition":\{"id":"\d+","user":\{"id":"\d+","displayName":"([^"]+)"', XXX)
|
|
346
|
+
author_display_name = m.group(1) if m else None
|
|
347
|
+
|
|
348
|
+
# 3) Petition created on DATE
|
|
349
|
+
m = re.search(r"Petition created on\s*([^<]+)", XXX)
|
|
350
|
+
created_on = m.group(1).strip() if m else None
|
|
351
|
+
|
|
352
|
+
# 4) ALL decision maker displayNames
|
|
353
|
+
decision_makers = re.findall(
|
|
354
|
+
r'"decisionMakers":\[\{"id":"\d+","slug":"[^"]+","displayName":"([^"]+)"',
|
|
355
|
+
XXX
|
|
356
|
+
)
|
|
357
|
+
decision_makers = list(dict.fromkeys(decision_makers)) # dedupe keep order
|
|
358
|
+
|
|
359
|
+
return {
|
|
360
|
+
"url": url,
|
|
361
|
+
"brief_description": brief_description,
|
|
362
|
+
"signatureCount": signatureCount,
|
|
363
|
+
"author_display_name": author_display_name,
|
|
364
|
+
"created_on": created_on,
|
|
365
|
+
"decision_makers": decision_makers,
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def get_all_info(list_of_petitions, sleep_sec=0.5):
|
|
372
|
+
list_of_info = []
|
|
373
|
+
|
|
374
|
+
for p in tqdm(list_of_petitions, desc="Fetching petition pages"):
|
|
375
|
+
pet_url = p.get("url")
|
|
376
|
+
if not pet_url:
|
|
377
|
+
continue
|
|
378
|
+
|
|
379
|
+
try:
|
|
380
|
+
info = scrape_change_org(pet_url) # <-- your function
|
|
381
|
+
list_of_info.append(info)
|
|
382
|
+
time.sleep(sleep_sec) # be polite / avoid getting blocked
|
|
383
|
+
|
|
384
|
+
except Exception as e:
|
|
385
|
+
list_of_info.append({
|
|
386
|
+
"url": pet_url,
|
|
387
|
+
"signatureCount": None,
|
|
388
|
+
"author_display_name": None,
|
|
389
|
+
"created_on": None,
|
|
390
|
+
"error": str(e)
|
|
391
|
+
})
|
|
392
|
+
|
|
393
|
+
return list_of_info
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def scrape_petitions(url,max_pages=None):
|
|
399
|
+
if max_pages==None:
|
|
400
|
+
print("No max pages specified, defaulting to 10 pages")
|
|
401
|
+
max_pages=10
|
|
402
|
+
else:
|
|
403
|
+
pass
|
|
404
|
+
list_of_petitions = get_petitions(url, max_pages=max_pages)
|
|
405
|
+
list_of_info = get_all_info(list_of_petitions)
|
|
406
|
+
|
|
407
|
+
# build table
|
|
408
|
+
rows = []
|
|
409
|
+
for p, info in zip(list_of_petitions, list_of_info):
|
|
410
|
+
rows.append({
|
|
411
|
+
"petition_title": p.get("Petition title"),
|
|
412
|
+
"url": p.get("url"),
|
|
413
|
+
**info
|
|
414
|
+
})
|
|
415
|
+
|
|
416
|
+
df = pd.DataFrame(rows)
|
|
417
|
+
|
|
418
|
+
# optional: drop duplicate url column coming from info dict
|
|
419
|
+
df = df.drop(columns=["url"], errors="ignore").assign(url=[p.get("url") for p in list_of_petitions])
|
|
420
|
+
|
|
421
|
+
return(df)
|
|
422
|
+
|
|
423
|
+
|
{changedotorgscraper-0.0.9 → ChangeDotOrgScraper-0.1.0}/ChangeDotOrgScraper.egg-info/PKG-INFO
RENAMED
|
@@ -1,29 +1,25 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: ChangeDotOrgScraper
|
|
3
|
-
Version: 0.0
|
|
3
|
+
Version: 0.1.0
|
|
4
4
|
Summary: Scrapes online petition data from change.org
|
|
5
5
|
Author: Charles Alba
|
|
6
6
|
Author-email: alba@wustl.edu
|
|
7
7
|
License: MIT
|
|
8
|
-
Keywords: change.org,petitions,web scraping
|
|
9
|
-
Classifier: Development Status ::
|
|
8
|
+
Keywords: change.org,petitions,web scraping,selenium,beautifulsoup
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
10
|
Classifier: Intended Audience :: Education
|
|
11
11
|
Classifier: Intended Audience :: Science/Research
|
|
12
12
|
Classifier: Programming Language :: Python :: 3
|
|
13
13
|
Classifier: Operating System :: Unix
|
|
14
14
|
Classifier: Operating System :: MacOS :: MacOS X
|
|
15
15
|
Classifier: Operating System :: Microsoft :: Windows
|
|
16
|
+
Requires-Python: >=3.8
|
|
16
17
|
Description-Content-Type: text/markdown
|
|
17
18
|
License-File: LICENSE
|
|
18
|
-
Requires-Dist: requests
|
|
19
|
-
Requires-Dist: bs4
|
|
20
|
-
Requires-Dist: tqdm
|
|
21
|
-
Requires-Dist: pandas
|
|
22
|
-
Requires-Dist: beautifulsoup4
|
|
23
19
|
|
|
24
20
|
`ChangeDotOrgScraper` is an Python package that allows you to scrape online petition data from [change.org](https://www.change.org/).
|
|
25
21
|
|
|
26
22
|
|
|
27
23
|
|
|
28
|
-
[](https://pypi.org/project/ChangeDotOrgScraper/) [](https://github.com/cja5553/change_org_scraper)
|
|
25
|
+
|
|
30
26
|
|
|
31
27
|
|
|
32
28
|
|
|
33
29
|
|
|
34
30
|
|
|
35
31
|
|
|
@@ -56,24 +52,29 @@ It returns a dataframe with all the petitions data, which contains details such
|
|
|
56
52
|
To use `ChangeDotOrgScraper`, you are required to have the following packages installed:
|
|
57
53
|
|
|
58
54
|
- `requests`
|
|
59
55
|
|
|
60
56
|
- `beautifulsoup4`
|
|
61
57
|
|
|
62
|
-
- `tqdm`
|
|
63
|
-
|
|
58
|
+
- `tqdm`
|
|
59
|
+
|
|
60
|
+
- `lxml`
|
|
61
|
+
|
|
62
|
+
- `selenium`
|
|
63
|
+
|
|
64
|
+
- `webdriver-manager`
|
|
65
|
+
|
|
64
66
|
- `pandas`
|
|
65
67
|
|
|
66
68
|
- `ast` (Python standard library)
|
|
67
69
|
|
|
68
70
|
- `re` (Python standard library)
|
|
69
71
|
|
|
70
72
|
- `json` (Python standard library)
|
|
71
73
|
|
|
74
|
+
- `time` (Python standard library)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
72
78
|
|
|
73
79
|
|
|
74
80
|
If you do not have these packages installed in python, you can do the following:
|
|
75
81
|
|
|
76
82
|
```bash
|
|
77
83
|
|
|
78
|
-
pip install requests beautifulsoup4 tqdm pandas
|
|
79
|
-
|
|
84
|
+
pip install requests beautifulsoup4 lxml tqdm pandas selenium webdriver-manager
|
|
85
|
+
|
|
80
86
|
```
|
|
81
87
|
|
|
82
88
|
|
|
83
89
|
|
|
84
90
|
|
|
85
91
|
|
|
86
92
|
## Citation
|
|
87
93
|
|
|
88
|
-
This package was made as part of a larger study on
|
|
89
|
-
|
|
94
|
+
This package was made as part of a larger study on policy-related opinion mining.
|
|
95
|
+
|
|
90
96
|
|
|
91
97
|
|
|
92
|
-
|
|
93
|
-
|
|
98
|
+
If you wish to cite, you may cite:
|
|
99
|
+
|
|
94
100
|
|
|
95
101
|
|
|
96
|
-
C
|
|
97
|
-
|
|
102
|
+
Alba, C., Warner, B. C., Saxena, A., Huang, J., & An, R. (2025, July). Towards robust sentiment analysis of temporally-sensitive policy-related online text. In Proceedings of the 63rd Annual Meeting of the Association for Computational Linguistics (Volume 4: Student Research Workshop) (pp. 958-976). doi: 10.18653/v1/2025.acl-srw.70
|
|
103
|
+
|
|
98
104
|
|
|
99
105
|
|
|
100
106
|
## Questions?
|
|
101
107
|
|
|
102
108
|
Contact me at [alba@wustl.edu](mailto:alba@wustl.edu)
|
|
103
109
|
|
|
@@ -1,29 +1,25 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: ChangeDotOrgScraper
|
|
3
|
-
Version: 0.0
|
|
3
|
+
Version: 0.1.0
|
|
4
4
|
Summary: Scrapes online petition data from change.org
|
|
5
5
|
Author: Charles Alba
|
|
6
6
|
Author-email: alba@wustl.edu
|
|
7
7
|
License: MIT
|
|
8
|
-
Keywords: change.org,petitions,web scraping
|
|
9
|
-
Classifier: Development Status ::
|
|
8
|
+
Keywords: change.org,petitions,web scraping,selenium,beautifulsoup
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
10
|
Classifier: Intended Audience :: Education
|
|
11
11
|
Classifier: Intended Audience :: Science/Research
|
|
12
12
|
Classifier: Programming Language :: Python :: 3
|
|
13
13
|
Classifier: Operating System :: Unix
|
|
14
14
|
Classifier: Operating System :: MacOS :: MacOS X
|
|
15
15
|
Classifier: Operating System :: Microsoft :: Windows
|
|
16
|
+
Requires-Python: >=3.8
|
|
16
17
|
Description-Content-Type: text/markdown
|
|
17
18
|
License-File: LICENSE
|
|
18
|
-
Requires-Dist: requests
|
|
19
|
-
Requires-Dist: bs4
|
|
20
|
-
Requires-Dist: tqdm
|
|
21
|
-
Requires-Dist: pandas
|
|
22
|
-
Requires-Dist: beautifulsoup4
|
|
23
19
|
|
|
24
20
|
`ChangeDotOrgScraper` is an Python package that allows you to scrape online petition data from [change.org](https://www.change.org/).
|
|
25
21
|
|
|
26
22
|
|
|
27
23
|
|
|
28
|
-
[](https://pypi.org/project/ChangeDotOrgScraper/) [](https://github.com/cja5553/change_org_scraper)
|
|
25
|
+
|
|
30
26
|
|
|
31
27
|
|
|
32
28
|
|
|
33
29
|
|
|
34
30
|
|
|
35
31
|
|
|
@@ -56,24 +52,29 @@ It returns a dataframe with all the petitions data, which contains details such
|
|
|
56
52
|
To use `ChangeDotOrgScraper`, you are required to have the following packages installed:
|
|
57
53
|
|
|
58
54
|
- `requests`
|
|
59
55
|
|
|
60
56
|
- `beautifulsoup4`
|
|
61
57
|
|
|
62
|
-
- `tqdm`
|
|
63
|
-
|
|
58
|
+
- `tqdm`
|
|
59
|
+
|
|
60
|
+
- `lxml`
|
|
61
|
+
|
|
62
|
+
- `selenium`
|
|
63
|
+
|
|
64
|
+
- `webdriver-manager`
|
|
65
|
+
|
|
64
66
|
- `pandas`
|
|
65
67
|
|
|
66
68
|
- `ast` (Python standard library)
|
|
67
69
|
|
|
68
70
|
- `re` (Python standard library)
|
|
69
71
|
|
|
70
72
|
- `json` (Python standard library)
|
|
71
73
|
|
|
74
|
+
- `time` (Python standard library)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
72
78
|
|
|
73
79
|
|
|
74
80
|
If you do not have these packages installed in python, you can do the following:
|
|
75
81
|
|
|
76
82
|
```bash
|
|
77
83
|
|
|
78
|
-
pip install requests beautifulsoup4 tqdm pandas
|
|
79
|
-
|
|
84
|
+
pip install requests beautifulsoup4 lxml tqdm pandas selenium webdriver-manager
|
|
85
|
+
|
|
80
86
|
```
|
|
81
87
|
|
|
82
88
|
|
|
83
89
|
|
|
84
90
|
|
|
85
91
|
|
|
86
92
|
## Citation
|
|
87
93
|
|
|
88
|
-
This package was made as part of a larger study on
|
|
89
|
-
|
|
94
|
+
This package was made as part of a larger study on policy-related opinion mining.
|
|
95
|
+
|
|
90
96
|
|
|
91
97
|
|
|
92
|
-
|
|
93
|
-
|
|
98
|
+
If you wish to cite, you may cite:
|
|
99
|
+
|
|
94
100
|
|
|
95
101
|
|
|
96
|
-
C
|
|
97
|
-
|
|
102
|
+
Alba, C., Warner, B. C., Saxena, A., Huang, J., & An, R. (2025, July). Towards robust sentiment analysis of temporally-sensitive policy-related online text. In Proceedings of the 63rd Annual Meeting of the Association for Computational Linguistics (Volume 4: Student Research Workshop) (pp. 958-976). doi: 10.18653/v1/2025.acl-srw.70
|
|
103
|
+
|
|
98
104
|
|
|
99
105
|
|
|
100
106
|
## Questions?
|
|
101
107
|
|
|
102
108
|
Contact me at [alba@wustl.edu](mailto:alba@wustl.edu)
|
|
103
109
|
|
|
@@ -7,11 +7,10 @@ readme_path = os.path.join(here, "README.md")
|
|
|
7
7
|
with codecs.open(readme_path, encoding="utf-8") as fh:
|
|
8
8
|
long_description = fh.read()
|
|
9
9
|
|
|
10
|
-
VERSION = '0.0
|
|
10
|
+
VERSION = '0.1.0'
|
|
11
11
|
DESCRIPTION = 'Scrapes online petition data from change.org'
|
|
12
12
|
LONG_DESCRIPTION = 'A package that scrapes online petition data from change.org, including the title, description, target audience, signature count, creator name, date created, location created, and victory status. Works by simply providing the url of the change.org petition search.'
|
|
13
13
|
|
|
14
|
-
# Setting up
|
|
15
14
|
setup(
|
|
16
15
|
name="ChangeDotOrgScraper",
|
|
17
16
|
version=VERSION,
|
|
@@ -21,16 +20,36 @@ setup(
|
|
|
21
20
|
long_description_content_type="text/markdown",
|
|
22
21
|
long_description=long_description,
|
|
23
22
|
packages=find_packages(),
|
|
24
|
-
install_requires=[
|
|
25
|
-
|
|
26
|
-
|
|
23
|
+
install_requires=[
|
|
24
|
+
"requests",
|
|
25
|
+
"beautifulsoup4",
|
|
26
|
+
"lxml",
|
|
27
|
+
"tqdm",
|
|
28
|
+
"pandas",
|
|
29
|
+
"selenium",
|
|
30
|
+
"webdriver-manager",
|
|
31
|
+
],
|
|
32
|
+
license="MIT",
|
|
33
|
+
keywords=["change.org", "petitions", "web scraping", "selenium", "beautifulsoup"],
|
|
27
34
|
classifiers=[
|
|
28
|
-
"Development Status ::
|
|
35
|
+
"Development Status :: 3 - Alpha",
|
|
29
36
|
"Intended Audience :: Education",
|
|
30
37
|
"Intended Audience :: Science/Research",
|
|
31
38
|
"Programming Language :: Python :: 3",
|
|
32
39
|
"Operating System :: Unix",
|
|
33
40
|
"Operating System :: MacOS :: MacOS X",
|
|
34
41
|
"Operating System :: Microsoft :: Windows",
|
|
35
|
-
]
|
|
42
|
+
],
|
|
43
|
+
python_requires=">=3.8",
|
|
36
44
|
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
@@ -1,185 +0,0 @@
|
|
|
1
|
-
import requests
|
|
2
|
-
from bs4 import BeautifulSoup
|
|
3
|
-
import json
|
|
4
|
-
from tqdm import tqdm
|
|
5
|
-
import re
|
|
6
|
-
import pandas as pd
|
|
7
|
-
import ast
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
def get_soup(url):
|
|
11
|
-
'''
|
|
12
|
-
Gets BeautifulSoup object from the url provided by the user.
|
|
13
|
-
|
|
14
|
-
Paramters:
|
|
15
|
-
- url (str): url link provided by the user
|
|
16
|
-
|
|
17
|
-
Returns:
|
|
18
|
-
- soup (BeautifulSoup obj): A beautiful object of the url provided by the user.
|
|
19
|
-
'''
|
|
20
|
-
if url.endswith("&offset=0"):
|
|
21
|
-
url=url[:url.find("offset=")]
|
|
22
|
-
url=url+"offset="
|
|
23
|
-
elif url.endswith("&offset="):
|
|
24
|
-
url=url
|
|
25
|
-
else:
|
|
26
|
-
url=url+"&offset="
|
|
27
|
-
|
|
28
|
-
# Send a GET request to the URL
|
|
29
|
-
response = requests.get(url+"0")
|
|
30
|
-
try:
|
|
31
|
-
# Parse the HTML content of the page with Beautiful Soup
|
|
32
|
-
soup = BeautifulSoup(response.text, 'html.parser')
|
|
33
|
-
except:
|
|
34
|
-
print("Please check the URL or change.org may have been updated such that this package is no long compatable")
|
|
35
|
-
return(soup)
|
|
36
|
-
|
|
37
|
-
def get_pages_no(soup):
|
|
38
|
-
'''
|
|
39
|
-
Determines the number of pages of worth of petitions within the change.org search.
|
|
40
|
-
|
|
41
|
-
Parameters:
|
|
42
|
-
- soup (BeautifulSoup obj): A beautiful object of the existing page of in the change.org petition of interests
|
|
43
|
-
|
|
44
|
-
Returns:
|
|
45
|
-
- offset_nos (list): list of page numbers.
|
|
46
|
-
'''
|
|
47
|
-
match = re.search(r'<div class="corgi-1weo53w">([\d,]+) results</div>', str(soup))
|
|
48
|
-
|
|
49
|
-
if match:
|
|
50
|
-
# Extract the matched group which contains the number of results
|
|
51
|
-
num_results = match.group(1)
|
|
52
|
-
# Optional: convert the string number to an integer, removing commas
|
|
53
|
-
num_results_int = int(num_results.replace(',', ''))
|
|
54
|
-
#print(num_results) # This will print the string
|
|
55
|
-
#print(num_results_int) # This will print the integer
|
|
56
|
-
else:
|
|
57
|
-
print("No match found")
|
|
58
|
-
offset=(num_results_int//10)*10
|
|
59
|
-
offset_nos=[i for i in range(0,offset+10,10)]
|
|
60
|
-
return(offset_nos)
|
|
61
|
-
|
|
62
|
-
def get_current_page(soup):
|
|
63
|
-
'''
|
|
64
|
-
Extracts all the petition and the corresponding creator information from the beautiful soup object.
|
|
65
|
-
|
|
66
|
-
Parameters:
|
|
67
|
-
- soup (BeautifulSoup obj): A beautiful object of the existing page of in the change.org petition of interests
|
|
68
|
-
|
|
69
|
-
Returns:
|
|
70
|
-
- petition_info (list): a list of dictionaries containing all the information of the petitions within the existing change.org page.
|
|
71
|
-
- creator_info (list): a list of dictionaries containing all the information of the corrresponding creators among the petitions within the existing change.org page.
|
|
72
|
-
'''
|
|
73
|
-
filter_soup=soup.find('script', text=lambda t: '__HYDRATION_DATA__' in t)
|
|
74
|
-
filter_soup=str(filter_soup)
|
|
75
|
-
start_str_pos=filter_soup.find("\"prefetchedData\":{\"")
|
|
76
|
-
end_str_pos=soup.find("}}}}")
|
|
77
|
-
info=filter_soup[start_str_pos:end_str_pos]
|
|
78
|
-
info=info.replace('</script>', '')
|
|
79
|
-
info=info.replace('<script>', '')
|
|
80
|
-
info=info.replace('__HYDRATION_DATA__=',"")
|
|
81
|
-
|
|
82
|
-
pattern = r'\{"petition":\{"__typename":"Petition".*?"highlight"'
|
|
83
|
-
|
|
84
|
-
# Find all instances in the text
|
|
85
|
-
matches = re.findall(pattern, info, re.DOTALL)
|
|
86
|
-
|
|
87
|
-
# Print matches
|
|
88
|
-
lists_of_petitions=[]
|
|
89
|
-
for match in (matches):
|
|
90
|
-
lists_of_petitions.append(match)
|
|
91
|
-
petition_info,creator_info=[],[]
|
|
92
|
-
petition_info_pattern = r'\{"petition":\{"__typename":"Petition".*?\}\}'
|
|
93
|
-
creator_info_pattern = r'"slug".*?"highlight"'
|
|
94
|
-
|
|
95
|
-
for i in lists_of_petitions:
|
|
96
|
-
petition_info.append(re.findall(petition_info_pattern, i, re.DOTALL))
|
|
97
|
-
creator_info.append(re.findall(creator_info_pattern, i, re.DOTALL))
|
|
98
|
-
petition_info=[item for sublist in petition_info for item in sublist]
|
|
99
|
-
creator_info=[item for sublist in creator_info for item in sublist]
|
|
100
|
-
|
|
101
|
-
for i in (range(len(lists_of_petitions))):
|
|
102
|
-
petition_info[i]=petition_info[i].replace('false', 'False').replace('true', 'True').replace('null', 'None')
|
|
103
|
-
petition_info[i]=ast.literal_eval(petition_info[i]+"}}")
|
|
104
|
-
creator_info[i]=creator_info[i].replace(",\"highlight\"","")
|
|
105
|
-
creator_info[i]="{"+creator_info[i]
|
|
106
|
-
# print(creator_info[i])
|
|
107
|
-
creator_info[i]= ast.literal_eval(creator_info[i].replace('false', 'False').replace('true', 'True').replace('null', 'None'))
|
|
108
|
-
return(petition_info,creator_info)
|
|
109
|
-
|
|
110
|
-
def clean_info(petition_info, creator_info):
|
|
111
|
-
'''
|
|
112
|
-
Organizes and parses all each petition and creator information
|
|
113
|
-
|
|
114
|
-
Parameters:
|
|
115
|
-
- petition_info (list): a list of dictionaries of petitions with informations of all the petitions within a change.org page.
|
|
116
|
-
Each dictionary contains information for each petition, which was extracted from `get_current_page` function.
|
|
117
|
-
- creator_info (list): a list of dictionaries with creator information from the corresponding petition in petition_info.
|
|
118
|
-
Each dictionary contains information for each creator of each corresponding petition, which was extracted from `get_current_page` function.
|
|
119
|
-
|
|
120
|
-
Returns
|
|
121
|
-
list_of_petitions (list): a list of dictionaries, with each dictionary containing information about the petition and creator from the list of petitions within one webpage.
|
|
122
|
-
These includes petition title, Description, signature count, creator name, date created, location createdd, and victory status.
|
|
123
|
-
'''
|
|
124
|
-
list_of_petitions=[]
|
|
125
|
-
for i,j in zip(petition_info,creator_info):
|
|
126
|
-
petition_title=i["petition"]["ask"]
|
|
127
|
-
petition_description=i["petition"]["description"]
|
|
128
|
-
# petition_target=i["petition"]["targetingDescription"]
|
|
129
|
-
petition_signatures=i["petition"]["signatureState"]["signatureCount"]["displayed"]
|
|
130
|
-
petition_creator=j["user"]["displayName"]
|
|
131
|
-
date_created=j['createdAt']
|
|
132
|
-
location=j["user"]["formattedLocationString"]
|
|
133
|
-
victory_verification_status=j['isVerifiedVictory']
|
|
134
|
-
curr={"Petition title":petition_title,
|
|
135
|
-
"Description":petition_description,
|
|
136
|
-
# "target":petition_target,
|
|
137
|
-
"signature count":petition_signatures,
|
|
138
|
-
"creator":petition_creator,
|
|
139
|
-
"date created":date_created,
|
|
140
|
-
"location created":location,
|
|
141
|
-
"Victory verification status":victory_verification_status}
|
|
142
|
-
list_of_petitions.append(curr)
|
|
143
|
-
return(list_of_petitions)
|
|
144
|
-
|
|
145
|
-
def scrape_petitions(url):
|
|
146
|
-
'''
|
|
147
|
-
Scrapes all the petition and its corresponding details based on the url provided.
|
|
148
|
-
This encompasses going looping through all the pages automatically to extract ALL the petitions, not just the petitions listed within the page itself.
|
|
149
|
-
|
|
150
|
-
Parameters:
|
|
151
|
-
- url (str): url from change.org upon searching for the list of petitions
|
|
152
|
-
|
|
153
|
-
Returns:
|
|
154
|
-
- data_of_petitions (pandas dataframe): dataset of petitions with all the relevant information, including
|
|
155
|
-
petition title, Description, target audience, signature count, creator name, date created, location createdd, and victory status.
|
|
156
|
-
'''
|
|
157
|
-
soup=get_soup(url)
|
|
158
|
-
# gets the list of page numbers.
|
|
159
|
-
pages=get_pages_no(soup)
|
|
160
|
-
list_of_petitions=[]
|
|
161
|
-
if url.endswith("&offset=0"):
|
|
162
|
-
url=url[:url.find("offset=")]
|
|
163
|
-
url=url+"offset="
|
|
164
|
-
elif url.endswith("&offset="):
|
|
165
|
-
url=url
|
|
166
|
-
else:
|
|
167
|
-
url=url+"&offset="
|
|
168
|
-
# this for loop runs through all the pages and extracts the petitions.
|
|
169
|
-
for (i) in tqdm(pages):
|
|
170
|
-
#print(f"obtaining page {i} of {pages[-1]} pages")
|
|
171
|
-
i=str(i)
|
|
172
|
-
response = requests.get(url+i)
|
|
173
|
-
try:
|
|
174
|
-
# Parse the HTML content of the page with Beautiful Soup
|
|
175
|
-
soup = BeautifulSoup(response.text, 'html.parser')
|
|
176
|
-
except:
|
|
177
|
-
print("Please check the URL or change.org may have been updated such that this package is no long compatable")
|
|
178
|
-
petition_info,creator_info=get_current_page(soup)
|
|
179
|
-
list_of_petitions+=clean_info(petition_info, creator_info)
|
|
180
|
-
data_of_petitions=pd.DataFrame(list_of_petitions)
|
|
181
|
-
return(data_of_petitions)
|
|
182
|
-
|
|
183
|
-
# example use case
|
|
184
|
-
# url = "https://www.change.org/search?q=Supplemental%20Nutrition%20Assistance%20Program&offset=0"
|
|
185
|
-
# SNAP_petitions=scrape_petitions(url)
|
|
File without changes
|
{changedotorgscraper-0.0.9 → ChangeDotOrgScraper-0.1.0}/ChangeDotOrgScraper.egg-info/SOURCES.txt
RENAMED
|
File without changes
|
|
File without changes
|
{changedotorgscraper-0.0.9 → ChangeDotOrgScraper-0.1.0}/ChangeDotOrgScraper.egg-info/top_level.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|