-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_parsing.py
74 lines (53 loc) · 2.49 KB
/
data_parsing.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
import urllib.request
from bs4 import BeautifulSoup
import pandas as pd
import urllib.error
def do_parsing(min_idx, max_idx):
sources = []
labels = []
for i in range(min_idx, max_idx):
# url текущей страницы
url = "http://ideone.com/recent/" + str(i)
# скачиваем страницу и создаём из неё объект soup
data = urllib.request.urlopen(url).read()
soup = BeautifulSoup(data, "lxml")
for block in soup.find_all('div', class_='source-view'):
spans = block.find_all('span')
# язык
language = spans[0].text
# отметка об успешности компиляции
valid_mark = spans[3].text
if valid_mark == 'Success':
# часть ссылки на страницу с кодом
link = block.find('strong').text
# файл с кодом находится по адресу http://ideone.com/plain/{переменная link}
# скачиваем его
response = urllib.request.urlopen('http://ideone.com/plain/' + link[1:])
data = response.read()
text = data.decode('utf-8')
# если кол-во строк в коде меньше 50, то добавляем
# текущий исходный код и метку языка в соответствующие списки
if text.count('\n') < 50:
sources.append(text)
labels.append(language)
return (sources, labels)
def write_to_new_dataframe(sources, labels):
df = pd.DataFrame({'source': sources, 'language': labels})
df.to_csv('data/raw_data.csv', index=False)
def append_to_dataframe(sources, labels):
df1 = pd.read_csv('raw_data.csv')
df2 = pd.DataFrame({'source': sources, 'language': labels})
# объединяем датафреймы
new_df = pd.concat([df1, df2])
# убираем дублирующиеся строки
new_df.drop_duplicates(inplace=True)
new_df.to_csv('raw_data.csv', index=False)
def stable_parse(min_idx, max_idx, step):
for i in range(min_idx, max_idx, step):
try:
sources, labels = do_parsing(i, i + step)
append_to_dataframe(sources, labels)
print('OK!')
except urllib.error.HTTPError:
print('Error! Continue...')
continue