Repository navigation
Expand file tree
/
Copy pathcommon.py
More file actions
209 lines (171 loc) · 7.49 KB
/
Copy pathcommon.py
File metadata and controls
209 lines (171 loc) · 7.49 KB
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
205
206
207
208
209
#!/usr/bin/env python3
"""
Common functions shared across Last.fm scraping scripts.
"""
import requests
from bs4 import BeautifulSoup
import sys
import time
from typing import List
from urllib.parse import urljoin
BASE_URL = 'https://www.last.fm'
def get_event_urls_from_page(url: str, verbose: bool = False) -> List[str]:
"""
Scrape event URLs from a user's events page.
Args:
url: URL of the events page
verbose: Print verbose debug information
Returns:
List of event URLs
"""
event_urls = []
max_retries = 3
for attempt in range(max_retries):
try:
if verbose:
print(f" Fetching: {url} (attempt {attempt + 1}/{max_retries})")
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
if response.status_code == 200:
if verbose:
print(f" Status: {response.status_code}")
soup = BeautifulSoup(response.content, 'html.parser')
# Find all event links - look for links with specific classes used by Last.fm
# Try multiple selectors to be more robust
event_links = []
# Look for event cards/items with specific classes
event_cards = soup.find_all(['div', 'li', 'article'], class_=lambda x: x and ('event' in x.lower() or 'card' in x.lower()))
for card in event_cards:
links = card.find_all('a', href=True)
event_links.extend(links)
# Also get all links and filter
all_links = soup.find_all('a', href=True)
event_links.extend(all_links)
if verbose:
print(f" Total links found: {len(event_links)}")
for link in event_links:
href = link['href']
if '/event/' in href:
if verbose:
print(f" Found event link: {href}")
full_url = urljoin(BASE_URL, href)
# Clean up the URL - remove query params and unwanted paths
full_url = full_url.split('?')[0]
# Remove trailing paths like /attendance, /going, /interested
for suffix in ['/attendance', '/going', '/interested', '/lineup']:
if full_url.endswith(suffix):
full_url = full_url[:-len(suffix)]
if full_url not in event_urls:
event_urls.append(full_url)
if verbose:
print(f" Found {len(event_urls)} unique event URLs")
break # Success, exit retry loop
else:
print(f" Status {response.status_code} for {url}, retrying in 30 seconds...", file=sys.stderr)
if attempt < max_retries - 1:
time.sleep(30)
else:
print(f" Failed after {max_retries} attempts", file=sys.stderr)
except requests.exceptions.RequestException as e:
print(f"Error fetching {url}: {e}", file=sys.stderr)
if verbose:
print(f" Full error: {repr(e)}")
if attempt < max_retries - 1:
print(f" Retrying in 30 seconds...", file=sys.stderr)
time.sleep(30)
else:
print(f" Failed after {max_retries} attempts", file=sys.stderr)
return event_urls
def get_all_event_urls(username: str, start_year: int = 2005, end_year: int = 2026, verbose: bool = False) -> List[str]:
"""
Get all event URLs for a user across multiple years.
Args:
username: Last.fm username
start_year: Starting year to search
end_year: Ending year to search
verbose: Print verbose debug information
Returns:
List of all event URLs
"""
all_event_urls = []
# Get events from main events page
print(f"Fetching events from main page...")
main_url = f"{BASE_URL}/user/{username}/events"
event_urls = get_event_urls_from_page(main_url, verbose)
all_event_urls.extend(event_urls)
print(f"Found {len(event_urls)} events on main page")
time.sleep(5) # Be nice to the server
# Get events from each year
for year in range(start_year, end_year + 1):
print(f"Fetching events from {year}...")
year_url = f"{BASE_URL}/user/{username}/events/{year}"
event_urls = get_event_urls_from_page(year_url, verbose)
# Add only new URLs
new_urls = [url for url in event_urls if url not in all_event_urls]
all_event_urls.extend(new_urls)
print(f"Found {len(new_urls)} new events in {year}")
time.sleep(5) # Be nice to the server
return all_event_urls
def fetch_page(url: str, verbose: bool = False, max_retries: int = 3) -> BeautifulSoup:
"""
Fetch and parse a web page with retry logic.
Args:
url: URL to fetch
verbose: Print verbose debug information
max_retries: Maximum number of retry attempts
Returns:
BeautifulSoup object or None if failed
"""
for attempt in range(max_retries):
try:
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
if response.status_code == 200:
return BeautifulSoup(response.content, 'html.parser')
else:
if verbose or attempt == max_retries - 1:
print(f"\n Status {response.status_code} for {url}, retrying in 30 seconds...", file=sys.stderr)
if attempt < max_retries - 1:
time.sleep(30)
else:
print(f" Failed after {max_retries} attempts", file=sys.stderr)
except requests.exceptions.RequestException as e:
if verbose or attempt == max_retries - 1:
print(f"\nError fetching {url}: {e}", file=sys.stderr)
if verbose:
print(f" Full error: {repr(e)}")
if attempt < max_retries - 1:
if verbose:
print(f" Retrying in 30 seconds...", file=sys.stderr)
time.sleep(30)
else:
if verbose:
print(f" Failed after {max_retries} attempts", file=sys.stderr)
return None
def print_progress(current: int, total: int, message: str = "Processing"):
"""
Print progress for a long-running operation.
Args:
current: Current item number (1-indexed)
total: Total number of items
message: Progress message prefix
"""
print(f"{message} {current}/{total}...", end='\r')
def write_to_file(content: str, filename: str, success_message: str = None):
"""
Write content to a file with error handling.
Args:
content: Content to write
filename: Output filename
success_message: Optional success message to print
Raises:
IOError: If writing fails
"""
try:
with open(filename, 'w', encoding='utf-8') as f:
f.write(content)
if success_message:
print(success_message)
else:
print(f"Results written to: {filename}")
except IOError as e:
print(f"Error writing to file: {e}", file=sys.stderr)
raise