mfgnik

Untitled

Oct 11th, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 0 0
  1. import bs4
  2. import requests
  3. from collections import deque
  4.  
  5.  
  6. class Parser:
  7.     _BAD_PREFIX_SET = {'Википедия:', 'Портал:'}
  8.  
  9.     def link_checker(self, link):
  10.         for prefix in self._BAD_PREFIX_SET:
  11.             if link['title'][:len(prefix)] == prefix:
  12.                 return False
  13.         return True
  14.  
  15.     def get_links(self, html):
  16.         soup = bs4.BeautifulSoup(html, features="html.parser")
  17.         css_selector = 'div.mw-parser-output a[href^=\/wiki]:not([class])'
  18.         links = soup.select(css_selector)
  19.         return list(map(lambda link: link['title'], filter(lambda x: self.link_checker(x), links)))
  20.  
  21.  
  22. class WebGraph:
  23.     def __init__(self, start, target):
  24.         self.start = start
  25.         self.target = target
  26.         self.parser = Parser()
  27.         self.used = {start: 0}
  28.  
  29.     @staticmethod
  30.     def build_link(link):
  31.         return f'https://ru.wikipedia.org/wiki/{link}'
  32.  
  33.     def bfs(self):
  34.         deq = deque()
  35.         deq.append(self.start)
  36.         while deq:
  37.             link = deq.popleft()
  38.             for other_link in self.parser.get_links(requests.get(self.build_link(link)).text):
  39.                 if other_link in self.used:
  40.                     continue
  41.                 if other_link == self.target:
  42.                     return self.used[link] + 1
  43.                 self.used[other_link] = self.used[link] + 1
  44.                 if self.used[other_link] > 5:
  45.                     break
  46.                 deq.append(other_link)
  47.  
  48.  
  49. graph = WebGraph('Соединённые Штаты Америки', 'Великобритания')
  50. print(graph.bfs())
Advertisement
Add Comment
Please, Sign In to add comment