]> code.communitydata.science - covid19.git/blob - wikipedia/scripts/wikiproject_scraper.py
renamed the wikipedia_views module to wikipedia
[covid19.git] / wikipedia / scripts / wikiproject_scraper.py
1 #!/usr/bin/env python3
2
3 ###############################################################################
4 #
5 # This script scrapes the Covid-19 Wikiproject
6
7 # It (1) hits the fcgi to find out how many rounds. Then (2) hit the fcgi 
8 # that many rounds, cooking that information down to just a list of article names and
9 # then (3) saves it out.
10 #
11 # At time of writing:
12 # the fCGI returns only 1000 max, no matter what you put in the limit. page 1 looks like this....
13 # https://tools.wmflabs.org/enwp10/cgi-bin/list2.fcgi?run=yes&projecta=COVID-19&namespace=&pagename=&quality=&importance=&score=&limit=1000&offset=1&sorta=Importance&sortb=Quality
14 #
15 # and page 2 looks like this
16 # https://tools.wmflabs.org/enwp10/cgi-bin/list2.fcgi?namespace=&run=yes&projecta=COVID-19&score=&sorta=Importance&importance=&limit=1000&pagename=&quality=&sortb=Quality&&offset=1001
17 #
18 ###############################################################################
19
20 import argparse
21 import subprocess
22 import requests
23 import datetime
24 import logging
25 import re
26 import math
27 from bs4 import BeautifulSoup
28
29 def parse_args():
30
31     parser = argparse.ArgumentParser(description='Get a list of pages tracked by the COVID-19 Wikiproject.')
32     parser.add_argument('-o', '--output_file', help='Where to save output', default="wikipedia/resources/enwp_wikiproject_covid19_articles.txt", type=str)
33     parser.add_argument('-L', '--logging_level', help='Logging level. Options are debug, info, warning, error, critical. Default: info.', default='info'), 
34     parser.add_argument('-W', '--logging_destination', help='Logging destination file. (default: standard error)', type=str), 
35     args = parser.parse_args()
36
37     return(args)
38
39 def main():
40
41     args = parse_args()
42     outputFile = args.output_file
43
44     #handle -L
45     loglevel_mapping = { 'debug' : logging.DEBUG,
46                          'info' : logging.INFO,
47                          'warning' : logging.WARNING,
48                          'error' : logging.ERROR,
49                          'critical' : logging.CRITICAL }
50
51     if args.logging_level in loglevel_mapping:
52         loglevel = loglevel_mapping[args.logging_level]
53     else:
54         print("Choose a valid log level: debug, info, warning, error, or critical") 
55         exit
56         
57     #handle -W
58     if args.logging_destination:
59         logging.basicConfig(filename=args.logging_destination, filemode='a', level=loglevel)
60     else:
61         logging.basicConfig(level=loglevel)
62
63     export_git_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode().strip()
64     export_git_short_hash = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode().strip()
65     export_time = str(datetime.datetime.now())
66
67     logging.info(f"Starting at {export_time} and destructively outputting article list to {outputFile}.")
68     logging.info(f"Last commit: {export_git_hash}")
69
70     #1 How many hits to the fcgi?
71     session = requests.Session()
72
73     originalURL = "https://tools.wmflabs.org/enwp10/cgi-bin/list2.fcgi?run=yes&projecta=COVID-19&namespace=&pagename=&quality=&importance=&score=&limit=1000&offset=1&sorta=Importance&sortb=Quality"
74     headURL = "https://tools.wmflabs.org/enwp10/cgi-bin/list2.fcgi?run=yes&projecta=COVID-19&namespace=&pagename=&quality=&importance=&score=&limit=1000&offset=" 
75     tailURL = "&sorta=Importance&sortb=Quality" #head + offset + tail = original when offset = 1
76
77     # find out how many results we have
78     response = session.get(originalURL)
79
80     soup = BeautifulSoup(response.text, features="html.parser")
81     nodes = soup.find_all('div', class_="navbox")
82     rx = re.compile("Total results:\D*(\d+)") 
83     m = rx.search(nodes[0].get_text())
84     #print(nodes[0].get_text())
85     numResults = int(m.group(1))
86
87     logging.debug(f"fcgi returned {numResults}")
88     rounds = math.ceil(numResults/1000) 
89
90     #2 Fetch and parse down to just the article names
91     articleNames = []
92
93     for i in range(1, rounds+1):
94         offset = (i - 1)*1000 + 1 #offset is 1, then 1001, then 2001 
95         url = f"{headURL}{offset}{tailURL}"
96         response = session.get(url)
97         soup = BeautifulSoup(response.text, features="html.parser") #make fresh soup
98         article_rows = soup.find_all('tr', class_="list-odd") #just the odds first
99         for row in article_rows:
100             a = row.find('a')
101             articleNames.append(a.get_text())
102         article_rows = soup.find_all('tr', class_="list-even") #now the events
103         for row in article_rows:
104             a = row.find('a')
105             articleNames.append(a.get_text())
106
107     #3 Saves the list to a file
108
109     with open(outputFile, 'w') as f:
110         f.write('\n'.join(articleNames)+'\n')
111     logging.debug(f"Finished scrape and made a new article file at {datetime.datetime.now()}")
112
113
114 if __name__ == "__main__":
115
116     main()
117

Community Data Science Collective || Want to submit a patch?