티스토리 뷰

IP주소 먼저 가져오기

위키백과를 둘러보면 사용자가 로그인한 상태에서 위키백과를 편집했다면 그 사용자 이름이 표시됩니다. 그렇지 않다면 사용자 이름 대신 IP주소가 기록됩니다. 이 IP를 freegeoip.not API에 문의하면 편집한 위치의 나라를 알려줍니다.


우리는 위키백과 개정 내역 페이지를 크롤링하고 IP 주소를 찾아내는 스크립트를 어렵지 않게 만들 수 있습니다.


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
from urllib.request import urlopen
from bs4 import BeautifulSoup
import datetime
import random
import re
 
random.seed(datetime.datetime.now())
def getLinks(articleUrl):
    html=urlopen("http://en.wikipedia.org"+articleUrl)
    bsObj=BeautifulSoup(html,"html.parser")
    return bsObj.find("div", {"id":"bodyContent"}).findAll("a",
        href=re.compile("^(/wiki/)((?!:).)*$"))
 
def getHistoryIPs(pageUrl):
    #개정 내역 페이지 URL은 다음과 같은 형식입니다.
    #http://en.sikipedia.org/w/index.php?title=Title_in_URL&action=history
    pageUrl=pageUrl.replace("/wiki/","")
    historyUrl="http://en.wikipedia.org/w/index.php?title="
    historyUrl+=pageUrl+"&action=history"
    print("history url is : "+historyUrl)
    html=urlopen(historyUrl)
    bsObj=BeautifulSoup(html,"html.parser")
    #사용자명 대신 IP 주소가 담긴, 클래스가 mw-anonuserlink인 링크만 찾습니다.
    ipAddresses=bsObj.findAll("a",{"class":"mw-anonuserlink"})
    adddressList=set()
    for ipAddress in ipAddresses:
        adddressList.add(ipAddress.get_text())
    return adddressList
 
links=getLinks("/wiki/Python_(programming_language)")
 
while(len(links)>0):
    for link in links:
        print("--------------------------")
        histroyIPs=getHistoryIPs(link.attrs["href"])
        for histroyIP in histroyIPs:
            print(histroyIP)
 
    newLink=links[random.randint(0,len(links)-1)].attrs["href"]
    links=getLinks(newLink)
cs



이 프로그램에는 메인 함수가 2개가 있습니다. 그 중 getHistoryIPs는 클래스가 mw-anonuserlink( 사용자 이름이 아니라 익명 사용자의  IP주소임을 나타내는 클래스)인 모든 링크 콘텐츠를 검색해서 파이썬 set으로 나타냅니다.


위 코드는 글 개정 내역을 가져올 항목을 찾습니다. 먼저 시작 페이지에 연결된 모든 위키백과 항목의 개정 내역을 가져옵니다. 그리고 무작위로 새 시작 페이지르르 선택한 다음, 그 페이지에 연결된 항목의 개정 내역을 가져옵니다. 링크가 없는 페이지를 만날 때까지 이 작업을 반복합니다.


IP주소를 국가로 변환하기

이제 IP 주소를 문자열로 가져오는 코드를 만들었으니, 이코드와 이전 섹션의 getCountry 함수를 결합해 이들 IP 주소를 국가로 변화할 겁니다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def getCountry(ipAddress):
    try:
        response=urlopen("http://freegeoip.net/json/"+ipAddress).read().decode("utf-8")
    except HTTPError:
        return None
    responseJson=json.loads(response)
    return responseJson.get("country_code")
 
links=getLinks("/wiki/Python_(programming_language)")
 
while(len(links)>0):
    for link in links:
        print("----------------------")
        historyIps=getHistoryIPs(link.attrs["href"])
        for historyIp in historyIps:
            country=getCountry(historyIp)
            if country is not None:
cs






※출처(파이썬으로 웹 크롤러 만들기)

'python > 웹 크롤링(python)' 카테고리의 다른 글

크롤링의 시작  (0) 2018.05.02
고급 HTML 분석  (0) 2018.05.01
BeautifulSoup 라이브러리  (0) 2018.05.01
urllib 라이브러리  (0) 2018.04.29
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함