1 Commits

2 changed files with 58 additions and 40 deletions
BIN
View File
Binary file not shown.
+58 -40
View File
@@ -1,45 +1,63 @@
import requests import sqlite3
from bs4 import BeautifulSoup
import re
url = 'https://msk.top-academy.ru/blog' db_name = 'mydb.db'
class BlogArticle: class User:
ls = list() def __init__(self,name,email,age):
def __init__(self,title,text): self.__id = None
self.title = title self.__name = name
self.text = text self.__email = email
BlogArticle.ls.append(self) self.__age = age
@classmethod
def count(cls):
return len(cls.ls)
def to_dict(self):
return {'title': self.title, 'text':self.text}
@classmethod @property
def from_dict(cls,d): def name(self):
BlogArticle(d['title'],d['text']) return self.__name
@name.setter
def name(self,value):
self.__name = value
@property
def email(self):
return self.__email
def scan(i): @email.setter
headers = { def email(self,value):
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36' if '@' in value:
} self.__email = value
response = requests.get( else:
url + (f'?page={i}' if i>1 else ''), raise ValueError('Не корректный адрес почты')
headers=headers @property
) def age(self):
html = response.text return self.__age
soup = BeautifulSoup(html,'html.parser') @age.setter
result = soup.find_all("div", class_='styles_cardBody__qP0jN') def age(self,value):
for el in result: if 0 <= value <= 120:
par = el.find_all("p") self.__age = value
BlogArticle(par[0].text,par[1].text) else:
raise ValueError('Неправильно указан возраст')
def save(self):
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
property_list = [f"{k}" for k, v in User.__dict__.items() if isinstance(v, property)]
if '_User__id' in self.__dict__.keys():
update_string = ','.join([f'`{p_name}`= ? ' for p_name in property_list])
update_values = [getattr(self,p) for p in property_list] + [self.__id]
query = f"UPDATE {User.__name__} SET {update_string} WHERE id = ?"
print(query,update_values)
else:
property_count = ('?,'*len(property_list))[:-1] #','.join(['?' for _ in range(len(property_list))])
property_names = ','.join(property_list)
property_values = [getattr(self,p) for p in property_list]
query = f"INSERT INTO {User.__name__}({property_names}) VALUES({property_count})"
print(query,property_values)
cursor.execute(query,property_values)
conn.commit()
self.__id = cursor.lastrowid
conn.close()
#print(User.__dict__)
if __name__ == '__main__': user1 = User('Igor','igor@example.com',44)
BlogArticle.from_dict({'title':'Заголовок','text':'Текст статьи'}) user1.save()
#for i in range(3): user1.age = 55
#scan(i) user1.save()
print(BlogArticle.count())
for i in range(1):
print(BlogArticle.ls[i].to_dict())