Created
May 7, 2016 06:31
-
-
Save hackerdem/af8145e84d845a9daf5a7adafbd007a5 to your computer and use it in GitHub Desktop.
extract wikipedia links and record them in a database table using python programming language
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
from urllib.request import urlopen | |
from bs4 import BeautifulSoup | |
import re | |
import random | |
import mysql.connector | |
global num | |
num=0 | |
def getlinks(articleurl): | |
html=urlopen("http://en.wikipedia.org{}".format(articleurl)) | |
response=BeautifulSoup(html,"html.parser") | |
return response.find("div",{"id":"bodyContent"}).findAll("a",href=re.compile("^(/wiki/)((?!:).)*$") | |
if __name__=='__main__': | |
cnx=mysql.connector.connect(user='****',password='******',host='********',database='******') | |
cursor=cnx.cursor() | |
links=getlinks("/wiki/Michael_Jackson") | |
while len(links)>0: | |
try: | |
data=[] | |
num+=1 | |
newarticle=links[random.randint(0,len(links)-1)].attrs["href"] | |
ini_query="INSERT INTO wiki1(id,link) VALUES(%s,%s);" | |
data=[num,newarticle] | |
cursor.execute(ini_query,data) | |
cnx.commit() | |
print(newarticle) | |
links=getlinks(newarticle) | |
except:pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment