Advertisement
Guest User

Получение списка страниц из категории

a guest
Jun 22nd, 2023
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. import time
  2. import requests
  3.  
  4. # https://www.mediawiki.org/wiki/API:Categorymembers
  5.  
  6. API_URL = "https://ru.wikipedia.org/w/api.php"
  7. USER_AGENT = {"User-Agent": "UsernameBot; email@example.com; python3.9; requests"}
  8.  
  9.  
  10. def get_category_members(title: str):
  11.     """
  12.    :param title: имя категории без префикса пространства имён
  13.    :return: список[] с именами страниц
  14.    """
  15.     result, cmcontinue = [], ""
  16.     params = {'action': 'query', 'list': 'categorymembers', 'cmtitle': f'Category:{title}', 'cmprop': 'title',
  17.               'cmnamespace': '0', 'cmtype': 'page', 'cmlimit': 'max', 'format': 'json', 'utf8': 1, 'maxlag': 5}
  18.     while cmcontinue is not None:
  19.         params['cmcontinue'] = cmcontinue
  20.  
  21.         while True:
  22.             r = requests.post(url=API_URL, data=params, headers=USER_AGENT).json()
  23.             if "error" in r and r['error']['code'] == "maxlag":
  24.                 time.sleep(int(r.headers['Retry-After']))
  25.             else:
  26.                 break
  27.  
  28.         cmcontinue = None if "continue" not in r else r['continue']['cmcontinue']
  29.         result.extend([page['title'] for page in r['query']['categorymembers']])
  30.         if cmcontinue is not None:
  31.             time.sleep(2)
  32.     return result
  33.  
  34.  
  35. print(*get_category_members("Актёры по алфавиту"), sep='\n')
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement