Last active
April 6, 2018 10:38
-
-
Save slothyrulez/a5cd7d5fd48cb46782805ae91c961e6c to your computer and use it in GitHub Desktop.
Basic Wikipedia scrapping
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import pprint | |
import lxml.html | |
from urllib import request | |
def get_page(url): | |
return request.urlopen(url) | |
def read_document(response): | |
return response.read() | |
def extract_data(document): | |
# Generate document tree | |
tree = lxml.html.fromstring(document) | |
# Select tr with a th and td descendant from table | |
elements = tree.xpath('//table[@class="infobox"]/tr[th and td]') | |
# Extract data | |
result = {} | |
for element in elements: | |
th, td = element.iterchildren() | |
result.update({ | |
th.text_content(): td.text_content() | |
}) | |
return result | |
if __name__ == "__main__": | |
languages = { | |
"python": "https://es.wikipedia.org/wiki/Python", | |
"Rust": "https://es.wikipedia.org/wiki/Rust_(lenguaje_de_programaci%C3%B3n)", | |
"Java": "https://es.wikipedia.org/wiki/Java_(lenguaje_de_programaci%C3%B3n)", | |
"Javascript": "https://es.wikipedia.org/wiki/JavaScript" | |
} | |
result = {} | |
for name, url in languages.items(): | |
response = get_page(url) | |
document = read_document(response) | |
result.update({name: extract_data(document)}) | |
pprint.pprint(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: