forked from wanicca/WikiHowQAExtractor-mnbvc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wikihow_parser.py
752 lines (633 loc) · 23.7 KB
/
wikihow_parser.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
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
"""
Some code from wikiHowUnofficialAPI
"""
from bs4 import BeautifulSoup
import urllib.request
from datetime import datetime
import re
class ParseError(RuntimeError):
""" Error parsing wikiHow page"""
class UnsupportedLanguage(ValueError):
""" Unsupported lang, see https://www.wikihow.com/wikiHow:Language-Projects"""
class Steps:
def __init__(self, number, title=None, description=None, picture=None):
self._number = number
self._title = title
self._description = description
self._picture = picture
def __repr__(self):
return '{} - {}'.format(self.number, self.title)
@property
def number(self):
"""Method to return the count of the current method.
Returns:
int: The count of the current method
"""
return self._number
@property
def title(self):
"""Method to return the title of a step.
Returns:
str: The title of a step
"""
return self._title
@property
def description(self):
"""Method to return the description given in a step.
Returns:
str: The description given in a step
"""
return self._description
@property
def picture(self):
"""Method to return the URL of image associated with the step.
Returns:
str: The URL of image associated with the step
"""
return self._picture
def get(self):
"""Method to return a dictionary of Steps data members.
Returns:
dict: A dictionary of Steps data members
"""
return {
'number': self.number,
'title': self.title,
'description': self.description,
'picture': self.picture
}
class Methods:
def __init__(self, number, title):
self._number = number
self._title = title
self._steps = []
def __repr__(self):
return '{} - {}'.format(self.number, self.title)
@property
def number(self):
"""Method to return the count of the current method.
Returns:
int: The count of the current method
"""
return self._number
@property
def title(self):
"""Method to return the title of a method.
Returns:
str: The title of a method
"""
return self._title
@property
def steps(self):
"""Method to return a list of steps in a method.
Returns:
list: A list of steps in a method
"""
return self._steps
def get(self):
"""Method to return a dictionary of Method data members.
Returns:
dict: A dictionary of Method data members
"""
return {
'number': self.number,
'title': self.title,
'steps': self.steps
}
class Article:
def __init__(self, content, lazy=False):
self.content = content
self._title = None
self._intro = None
self._methods = []
self._num_votes = None
self._percent_helpful = None
self._is_expert = None
self._last_updated = None
self._views = None
self._co_authors = None
self._references = None
self._summary = None
self._warnings = {"title":"","warnings":[]}
self._tips = {"title":"","tips":[]}
self._parsed = False
if not lazy:
self._parse()
def __repr__(self):
return self.title
# @property
# def url(self):
# """Method to return the URL of a wikiHow article.
# Returns:
# str: The wikiHow article URL
# """
# if not self._parsed:
# self._parse()
# return self._url
@property
def title(self):
"""Method to return the title of a wikiHow article.
Returns:
str: The wikiHow article title
"""
if not self._parsed:
self._parse()
return self._title
@property
def intro(self):
"""Method to return the introduction from a wikiHow article.
Returns:
str: The wikiHow article introduction
"""
if not self._parsed:
self._parse()
return self._intro
@property
def methods(self):
"""Method to return the method titles from a wikiHow article.
Returns:
list: A list of method titles
"""
if not self._parsed:
self._parse()
return self._methods
@property
def n_methods(self):
"""Method to return the number of methods in a wikiHow article.
Returns:
int: The number of methods in a wikiHow article
"""
return len(self._methods)
@property
def num_votes(self):
"""Method to return the number of votes given to a wikiHow article.
Returns:
int: The number of votes given to a wikiHow article
"""
if not self._parsed:
self._parse()
return self._num_votes
@property
def percent_helpful(self):
"""Method to return the percent of helpful recieved by a wikiHow article.
Returns:
int: The percent of helpful recieved by a wikiHow article
"""
if not self._parsed:
self._parse()
return self._percent_helpful
@property
def is_expert(self):
"""Method to check if a wikiHow article is written by an expert.
Returns:
bool: True if written by an expert, False otherwise.
"""
if not self._parsed:
self._parse()
return self._is_expert
@property
def last_updated(self):
"""Method to return the last date when a wikiHow article was updated. (Format: YYYY-MM-DD HH: MM: SS)
Returns:
str: The last date when a wikiHow article was updated.
"""
if not self._parsed:
self._parse()
return self._last_updated
@property
def views(self):
"""Method to return the number of times a wikiHow article was viewed.
Returns:
int: Number of times a wikiHow article was viewed.
"""
if not self._parsed:
self._parse()
return self._views
@property
def co_authors(self):
"""Method to return the number of co-authors in a wikiHow article.
Returns:
int: Number of co-authors in a wikiHow article.
"""
if not self._parsed:
self._parse()
return self._co_authors
@property
def references(self):
"""Method to return the number of references in a wikiHow article.
Returns:
int: Number of references in a wikiHow article.
"""
if not self._parsed:
self._parse()
return self._references
@property
def summary(self):
"""Method to return the summary of a wikiHow article.
Returns:
str: summary of a wikiHow article.
"""
if not self._parsed:
self._parse()
return self._summary
@property
def warnings(self):
"""Method to return a list of warnings from a wikiHow article.
Returns:
list: Warnings from a wikiHow article.
"""
if not self._parsed:
self._parse()
return self._warnings
@property
def tips(self):
"""Method to return a list of tips from a wikiHow article.
Returns:
list: Tips from a wikiHow article.
"""
if not self._parsed:
self._parse()
return self._tips
def _parse_title(self, soup):
"""Method to extract the title of a wikiHow article.
Args:
soup(bs4.BeautifulSoup): An instance of BeautifulSoup class for the entire article.
Raises:
ParseError: The given article could not be parsed.
"""
html = soup.findAll(
'h1', {'class': ['title_lg', 'title_md', 'title_sm']})[0]
if not html.find('a'):
raise ParseError
else:
self._title = html.text
def _parse_intro(self, soup):
"""Method to extract the introduction from a wikiHow article.
Args:
soup(bs4.BeautifulSoup): An instance of BeautifulSoup class for the entire article.
Raises:
ParseError: The given article could not be parsed.
"""
intro_html = soup.find('div', {'class': 'mf-section-0'})
if not intro_html:
raise ParseError
else:
super = intro_html.find('sup')
if super != None:
for sup in intro_html.findAll('sup'):
sup.decompose()
intro = intro_html.text
self._intro = intro.strip()
else:
intro = intro_html.text
self._intro = intro.strip()
def _parse_methods(self, soup):
"""Method to extract the methods from a wikiHow article.
Args:
soup(bs4.BeautifulSoup): An instance of BeautifulSoup class for the entire article.
Raises:
ParseError: The given article could not be parsed.
"""
self._methods = []
methods_html = soup.findAll(
'div', {'class': ['section steps steps_first sticky', 'section steps sticky','section steps steps_first sticky hide_step_numbers','section steps sticky hide_step_numbers']})
if not methods_html:
raise ParseError
else:
count = 0
for method_html in methods_html:
span = method_html.find('span', {'class': 'mw-headline'})
count += 1
title = span.text
method = Methods(count, title)
self._methods.append(method)
step_html = method_html.findAll('div', {'class': 'step'})
pic_count = 0
pictures_list = [None] * len(step_html)
for list_html in method_html.findAll('ol'):
for list in list_html.findAll('li', {'id': re.compile('step.+')}):
html = list.find('a', {'class': 'image'})
# handling case when there are no images or for when there are videos/gifs instead of images
if html != None:
html = html.find('img')
i = str(html).find('data-src=')
pic = str(html)[i:].replace('data-src="', '')
pic = pic[:pic.find('"')]
pictures_list[pic_count] = pic
pic_count += 1
count_steps = 0
for html in step_html:
# exception handling because not all steps have a summary
try:
super = html.find('sup')
script = html.find('script')
if script != None:
for script in html.findAll('script'):
script.decompose()
if super != None:
for sup in html.findAll('sup'):
sup.decompose()
count_steps += 1
summary = html.find('b').text
for _extra_div in html.find('b').find_all('div'):
summary = summary.replace(_extra_div.text, '')
except:
summary = ''
step = Steps(count_steps, summary)
ex_step = html
for b in ex_step.findAll('b'):
b.decompose()
step._description = ex_step.text.strip()
step._picture = pictures_list[count_steps-1]
self._methods[count-1]._steps.append(step)
def _parse_votes_n_helpful(self, soup):
"""Method to extract the number of helpful votes and helpful percentage given to a wikiHow article.
Args:
soup(bs4.BeautifulSoup): An instance of BeautifulSoup class for the entire article.
Raises:
ParseError: The given article could not be parsed.
"""
num_votes_html = soup.find('div', {'class': 'sp_helpful_rating_count'})
if num_votes_html:
if str(num_votes_html) == '<div class="sp_helpful_rating_count"></div>':
return
content = str(num_votes_html)
self._num_votes = int(''.join(
(content[content.find('>')+1: content.find(' votes')]).split(',')))
self._percent_helpful = int(content[content.find(
'- ')+2:content.find('%</div>')])
def _parse_is_expert(self, soup):
"""Method to check if a wikiHow article is written by an expert.
Args:
soup(bs4.BeautifulSoup): An instance of BeautifulSoup class for the entire article.
Raises:
ParseError: The given article could not be parsed.
"""
expert_html = soup.find('div', {'id': 'byline_info'})
if not expert_html:
raise ParseError
else:
b = expert_html.find('b')
if b:
self._is_expert = True
else:
self._is_expert = False
def _parse_last_updated(self, soup):
"""Method to extract the date of last update of a wikiHow article.
Args:
soup(bs4.BeautifulSoup): An instance of BeautifulSoup class for the entire article.
Raises:
ParseError: The given article could not be parsed.
"""
update_html = soup.find('div', {'id': 'byline_info'})
if not update_html:
raise ParseError
else:
try:
span = str(update_html.find('span'))
date = span[span.find(': ')+2:span.find('</span>')]
self._last_updated = datetime.strptime(date, '%B %d, %Y')
except:
pass
def _parse_views(self, soup):
"""Method to extract the number of views in a wikiHow article.
Args:
soup(bs4.BeautifulSoup): An instance of BeautifulSoup class for the entire article.
Raises:
ParseError: The given article could not be parsed.
"""
views_html = soup.find('div', {'class': 'sp_box sp_stats_box'})
if views_html:
div = views_html.findAll('div', {'class': 'sp_text'})
span = str(div[2].find('span', {'class': 'sp_text_data'}))
self._views = int(
''.join((span[span.find('>')+1: span.find('</span>')]).split(',')))
else:
pass
def _parse_co_authors(self, soup):
"""Method to extract the number of co-authors in a wikiHow article.
Args:
soup(bs4.BeautifulSoup): An instance of BeautifulSoup class for the entire article.
Returns:
None: When no co-authors are found.
"""
co_authors_html = soup.find('div', {'class': 'sp_box sp_stats_box'})
if not co_authors_html:
return None
else:
div = co_authors_html.findAll('div', {'class': 'sp_text'})
span = str(div[0].find('span', {'class': 'sp_text_data'}))
self._co_authors = int(''.join(
(span[span.find('>')+1: span.find('</span>')]).split(',')))
def _parse_references(self, soup):
"""Method to extract the number of references in a wikiHow article.
Args:
soup(bs4.BeautifulSoup): An instance of BeautifulSoup class for the entire article.
Returns:
None: When no references are found.
"""
references_html = soup.findAll('a', {'class': 'external free'})
count = 0
if not references_html:
return None
else:
for reference in references_html:
count += 1
self._references = count
def _parse_summary(self, soup):
"""Method to extract summary from a wikiHow article.
Args:
soup(bs4.BeautifulSoup): An instance of BeautifulSoup class for the entire article.
Returns:
None: When no summary is found.
"""
summary_html_div = soup.find('div', {'id': 'summary_wrapper'})
if not summary_html_div:
return None
else:
summary_html = summary_html_div.find('p', {'id': 'summary_text'})
summary = summary_html.text[:-35]
self._summary = summary
def _parse_warnings(self, soup):
"""Method to extract warnings from a wikiHow article.
Args:
soup(bs4.BeautifulSoup): An instance of BeautifulSoup class for the entire article.
Returns:
None: When no warnings are found.
"""
warnings_html_div = soup.find('div', {'id': ['warnings','警告']})
if not warnings_html_div:
self._warnings = {}
return None
else:
self._warnings['title']=warnings_html_div.findPreviousSibling().text.strip()
warnings_html = warnings_html_div.find('ul')
if warnings_html != None:
for li in warnings_html.findAll('li',recursive=False):
# if not li.find('div'):
# return None
# self._warnings.append(li.find('div').text)
vote = li.find('div',{"class":"wh_vote_container"})
if vote:
vote.decompose()
self._warnings['warnings'].append(li.text)
else:
warnings_html = warnings_html_div.find('p')
if warnings_html != None:
self._warnings['warnings'].append(warnings_html.text)
else:
return None
def _parse_tips(self, soup):
"""Method to extract tips from a wikiHow article.
Args:
soup(bs4.BeautifulSoup): An instance of BeautifulSoup class for the entire article.
Returns:
None: When no tips are found.
"""
tips_html_div = soup.find('div', {'id': ['tips','小提示']})
if not tips_html_div:
self._tips = {}
return None
else:
self._tips['title']=tips_html_div.findPreviousSibling().text
tips_html = tips_html_div.find('ul')
if tips_html != None:
for li in tips_html.findAll('li',recursive=False):
# if not li.find('div'):
# return None
# else:
# self._tips.append(li.find('div').text)
vote = li.find('div',{"class":"wh_vote_container"})
if vote:
vote.decompose()
self._tips['tips'].append(li.text.strip())
else:
tips_html = tips_html_div.find('p')
if tips_html != None:
self._tips['tips'].append(tips_html.text.strip())
else:
return None
def _parse(self):
"""Method to extract useful information from a given wikiHow article.
Raises:
ParseError: The given article could not be parsed.
"""
try:
# content = urllib.request.urlopen(self._url)
# read_content = content.read()
soup = BeautifulSoup(self.content, 'html.parser')
self._parse_title(soup)
self._parse_intro(soup)
self._parse_methods(soup)
self._parse_votes_n_helpful(soup)
self._parse_is_expert(soup)
self._parse_last_updated(soup)
self._parse_views(soup)
self._parse_co_authors(soup)
self._parse_references(soup)
self._parse_summary(soup)
self._parse_warnings(soup)
self._parse_tips(soup)
self._parsed = True
except Exception as e:
raise ParseError
def get(self):
"""Method to return a dictionary of class members.
Returns:
dict: A dictionary of class members.
"""
return {
# 'url': self.url,
'title': self.title,
'intro': self.intro,
'n_methods': self.n_methods,
'methods': self.methods,
'num_votes': self.num_votes,
'percent_helpful': self.percent_helpful,
'is_expert': self.is_expert,
'last_updated': self.last_updated,
'views': self.views,
'co_authors': self.co_authors,
'references': self.references,
'summary': self.summary,
'warnings': self.warnings,
'tips': self.tips
}
# class WikiHow:
# lang2url = {
# 'en': 'http://www.wikihow.com/',
# 'es': 'http://es.wikihow.com/',
# 'pt': 'http://pt.wikihow.com/',
# 'it': 'http://www.wikihow.it/',
# 'fr': 'http://fr.wikihow.com/',
# 'ru': 'http://ru.wikihow.com/',
# 'de': 'http://de.wikihow.com/',
# 'zh': 'http://zh.wikihow.com/',
# 'nl': 'http://nl.wikihow.com/',
# 'cz': 'http://www.wikihow.cz/',
# 'id': 'http://id.wikihow.com/',
# 'jp': 'http://www.wikihow.jp/',
# 'hi': 'http://hi.wikihow.com/',
# 'th': 'http://th.wikihow.com/',
# 'ar': 'http://ar.wikihow.com/',
# 'ko': 'http://ko.wikihow.com/',
# 'tr': 'http://www.wikihow.com.tr/',
# 'vn': 'http://www.wikihow.vn/'
# }
# @ staticmethod
# def search(search_term, max_results=-1, lang='en'):
# """Method to search for wikiHow articles.
# Args:
# search_term(str): [description]
# max_results(int, optional): Number of results. Defaults to - 1.
# lang(str, optional): Language of the wikiHow articles. Defaults to 'en'.
# Raises:
# UnsupportedLanguage: There are no wikiHow articles with this language.
# Yields:
# str: One of the search results.
# """
# lang = lang.split('-')[0].lower()
# if lang not in WikiHow.lang2url:
# raise UnsupportedLanguage
# search_url = WikiHow.lang2url[lang] + \
# 'wikiHowTo?search='+urllib.parse.quote(search_term)
# content = urllib.request.urlopen(search_url)
# read_content = content.read()
# soup = BeautifulSoup(read_content, 'html.parser').findAll('a', attrs={
# 'class': 'result_link'})
# count = 1
# for link in soup:
# url = link.get('href')
# if not url.startswith('http'):
# url = 'http://' + url
# how_to = Article(url)
# try:
# how_to._parse()
# except ParseError:
# continue
# yield how_to
# count += 1
# if 0 < max_results < count:
# return
# def random_article(lang='en'):
# """Method to return a random wikiHow article.
# Args:
# lang(str, optional): Language of the wikiHow article. Defaults to 'en'.
# Returns:
# str: URL of the article.
# """
# url = WikiHow.lang2url[lang] + 'Special:Randomizer'
# return Article(url)
# def search_wikihow(query, max_results=10, lang='en'):
# """Method to search and return a list of wikHow articles.
# Args:
# query(str): Search string
# max_results(int, optional): Number of search results. Defaults to 10.
# lang(str, optional): Language of the wikiHow articles. Defaults to 'en'.
# Returns:
# list: A list containing the names of the Wikhow articles from the search result.
# """
# return list(WikiHow.search(query, max_results, lang))
# if __name__ == '__main__':
# """This file can only be loaded as a module."""
# exit()