Created
June 8, 2022 09:59
-
-
Save codeboy/e823ced7c5c0da4f6603bc5d4f655d7c to your computer and use it in GitHub Desktop.
example of counting html tags
This file contains 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
# Код для парсинга немного избыточен, однако так нагляднее | |
# Здесь добавление экшенов в кастомном парсере для подсчёта тегов | |
# Так же полный словарь с количеством каждого элемента | |
# тегов в коде главной страницы - count 1072 | |
# из них содержит атрибуты - tags_with_attr 982 | |
from html.parser import HTMLParser | |
from collections import defaultdict | |
from urllib.request import urlopen | |
class MyHTMLParser(HTMLParser): | |
''' | |
для того, что бы сам парсер заработал, надо добавить методы обработки | |
''' | |
def __init__(self): | |
self.alltags = defaultdict(int) # словарь с тегами | |
self.count = int() # количество всех тегов | |
self.tags_with_attr = int() # количество тэгов с атрибутами | |
super().__init__() | |
def handle_starttag(self, tag, attrs): | |
self.alltags[tag] += 1 | |
self.count += 1 | |
if len(attrs) >= 1: | |
self.tags_with_attr += 1 | |
def handle_startendtag(self, tag, attrs): | |
self.alltags[tag] += 1 | |
self.count += 1 | |
if len(attrs) >= 1: | |
self.tags_with_attr += 1 | |
def count_tags(html): | |
parser = MyHTMLParser() | |
parser.feed(html) | |
return { | |
'alltags': parser.alltags, | |
'count': parser.count, | |
'tags_with_attr': parser.tags_with_attr, | |
} | |
link = urlopen('http://www.jetlend.ru') | |
if link.getcode() == 200: | |
content = link.read().decode("utf-8") | |
parsed = count_tags(content) | |
for i in parsed: | |
print(i, parsed[i]) | |
else: | |
print('Some error happend') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment