2014-06-19 2 views
1

주어진 위키피디아 페이지에서 다른 위키피디아 기사 및 모든 해당 카테고리로 모든 나가는 링크를 얻으려고합니다.왜이 위키 백과 mediawiki API 요청은 카테고리를 모든 링크로 반환하지 않습니까?

어쨌든 많은 페이지는 분명히 일부 페이지에 속하지만 카테고리가없는 경우에도 반환됩니다. 체계적이지 않은 것처럼 보입니다. 즉 카테고리없이 반환 된 페이지가 항상 동일하지는 않습니다. 경우 누군가에

# -*- coding: utf-8 -*- 
import urllib.request 
import urllib.parse 
import json 

def link_request(more_parameters={"continue": ""}): 
    parameters = {"format": "json", 
       "action": "query", 
       "generator": "links", 
       "gpllimit": "max", 
       "gplnamespace": "0", 
       "prop": "categories", 
       "cllimit": "max", 
       "titles": urllib.parse.quote(start_page.encode("utf8"))} 
    parameters.update(more_parameters) 

    queryString = "&".join("%s=%s" % (k, v) for k, v in parameters.items()) 

    # This ensures that redirects are followed automatically, documented here: 
    # http://www.mediawiki.org/wiki/API:Query#Resolving_redirects 
    queryString = queryString+"&redirects" 

    url = "http://%s.wikipedia.org/w/api.php?%s" % (wikipedia_language, queryString) 
    print(url) 

    #get json data from wikimedia API and make a dictionary out of it: 
    request = urllib.request.urlopen(url) 
    encoding = request.headers.get_content_charset() 
    jsonData = request.read().decode(encoding) 
    data = json.loads(jsonData) 

    return data 

def get_link_data(): 
    data=link_request() 

    query_result=data['query']['pages'] 

    while 'continue' in data.keys(): 
     continue_dict=dict() 
     for key in list(data['continue'].keys()): 
     if key == 'continue': 
      continue_dict.update({key: data['continue'][key]}) 
     else: 
      val= "|".join([urllib.parse.quote(e) for e in data['continue'][key].split('|')]) 
      continue_dict.update({key: val}) 
     data=link_request(continue_dict) 
     query_result.update(data['query']['pages']) 

    print(json.dumps(query_result, indent=4)) 

start_page="Albert Einstein" 
wikipedia_language="en" 
get_link_data() 

가 궁금해 : 그것은 내가 할 수있는

다음의 예는 최소한 계속 물건은 여기에 설명 : http://www.mediawiki.org/wiki/API:Query#Continuing_queries

답변

2

문제는 그 때문에 길이다 계속 작업하면 결과가 update() 일 뿐이며 작동 할 것이라고 기대할 수는 없습니다.

  • 페이지 1
    • 카테고리 1
  • 2 페이지
    • 구분 2A
    • 카테고리 2B : 예를 들어

      , 당신은 범주 다음과 같은 링크 된 페이지를했다 상상

  • 3 페이지
    • 카테고리 3
  • 이제

, 당신은 모두 gpllimit 및 2-cllimit를 설정 한 경우 (즉,각 응답은 세 가지가이 같은 반응을 계속 통해 결과가 될 것입니다, 최대 두 페이지와 그 범주의 최대 2 개씩)가 포함됩니다 :

  • 응답을 1
    • 페이지 1
      • 카테고리 1
    • 2 페이지
      • 구분 2A
  • 응답 2
    • 페이지 1
    • 2 페이지
      • 카테고리 2B
  • 응답 3
    • 3 페이지 0,123,516
      • 카테고리는 이러한 응답을 결합 update()을 사용하려고하는 경우, 응답 2의 결과는 응답 1 결과를 덮어 씁니다 3

:

  • 페이지 1
  • 페이지 2
    • 카테고리 2B
  • 3 페이지
    • 카테고리는 3

그럼, 당신이해야 할 것은 응답을 결합하는 현명한 방법을 사용하는 것입니다. 또는 더 좋게는 one of the existing libraries to access the API을 사용하십시오.