-
Notifications
You must be signed in to change notification settings - Fork 0
/
scraper.py
65 lines (50 loc) · 1.78 KB
/
scraper.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
import requests
import lxml.html as html
import os
import datetime
#CNN Music
LINK_CNN_MUSIC = 'https://cnnespanol.cnn.com/category/musica/'
XPATH_LINK_TO_ARTICLE = '//h2[@class="news__title"]/a/@href'
XPATH_TITLE = '//div[@class="news__data"]/h1[@class="news__title"]/text()'
XPATH_CONTAIN = '//div[@class="news__excerpt"]/p/text()'
def parse_notices(link, today):
try:
response = requests.get(link)
if response.status_code == 200:
notice = response.content.decode('utf-8')
parsed = html.fromstring(notice)
try:
title = parsed.xpath(XPATH_TITLE)[0]
title = title.replace('\"','').strip()
contain = parsed.xpath(XPATH_CONTAIN)[0]
except IndexError:
return
with open(f'{today}/{title}.txt', 'w', encoding='utf-8') as f:
f.write(title)
f.write('\n\n')
f.write(contain)
else:
raise ValueError(f'Error: {respones.status_code}')
except ValueError as ve:
print(ve)
def parse_home():
try:
response = requests.get(LINK_CNN_MUSIC)
if response.status_code == 200:
home = response.content.decode('utf-8')
parsed = html.fromstring(home)
links_to_notices = parsed.xpath(XPATH_LINK_TO_ARTICLE)
# print(links_to_notices)
today = datetime.date.today().strftime('%d-%m-%Y')
if not os.path.isdir(today):
os.mkdir(today)
for link in links_to_notices:
parse_notices(link, today)
else:
raise ValueError(f'Error: {status_code}')
except ValueError as ve:
print(ve)
def run():
parse_home()
if __name__ == '__main__':
run()