1 Commits

Author SHA1 Message Date
laktionov-as 3099949f6c Написали класс для сканирования 2026-06-10 19:40:24 +03:00
2 changed files with 73 additions and 39 deletions
BIN
View File
Binary file not shown.
+73 -39
View File
@@ -1,45 +1,79 @@
import requests import requests
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
import re import re
import sqlite3
from datetime import datetime
url = 'https://msk.top-academy.ru/blog' class Spyder:
def __init__(self):
class BlogArticle: self.db_name = 'database.db'
ls = list() self.conn = sqlite3.connect(self.db_name)
def __init__(self,title,text): self.cursor = self.conn.cursor()
self.title = title def init_db(self):
self.text = text query = '''CREATE TABLE links(
BlogArticle.ls.append(self) id INTEGER PRIMARY KEY AUTOINCREMENT,
@classmethod link TEXT NOT NULL,
def count(cls): last_scan INTEGER DEFAULT 0,
return len(cls.ls) title TEXT DEFAULT ''
)'''
def to_dict(self): self.cursor.execute(query)
return {'title': self.title, 'text':self.text} def scan(self,url):
if url.endswith('.pdf'):
@classmethod return
def from_dict(cls,d): headers = {
BlogArticle(d['title'],d['text']) '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'
}
def scan(i): try:
headers = { response = requests.get(
'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' url,
} headers=headers,
response = requests.get( timeout=5
url + (f'?page={i}' if i>1 else ''), )
headers=headers except:
) self.update_url(url,'Scan error')
html = response.text return
soup = BeautifulSoup(html,'html.parser') html = response.text
result = soup.find_all("div", class_='styles_cardBody__qP0jN') soup = BeautifulSoup(html,'html.parser')
for el in result: result = soup.find_all("a", href=True)
par = el.find_all("p") title = soup.title.text
BlogArticle(par[0].text,par[1].text) self.update_url(url,title)
for el in result:
if el['href'].endswith('.pdf'):
continue
if not el['href'].startswith('http'):
match = re.findall(r'https?://[A-Za-z0-9.-]+',url)
link = f"{match[0]}{el['href']}"
else:
link = el['href']
query = f'SELECT id FROM links WHERE link = ?'
self.cursor.execute(query,(link,))
if self.cursor.fetchone():
continue
query = f'INSERT INTO links(link) VALUES(?)'
self.cursor.execute(query,(link,))
self.conn.commit()
def update_url(self,url,title):
query = "SELECT id FROM links WHERE link = ?"
self.cursor.execute(query,(url,))
link_id = self.cursor.fetchone()
if link_id:
query = "UPDATE links SET title=?, last_scan=? WHERE id=?"
self.cursor.execute(query,(title,datetime.now().timestamp(),link_id[0]))
self.conn.commit()
def get_url(self):
query = "SELECT link FROM links ORDER BY last_scan LIMIT 1"
self.cursor.execute(query)
return self.cursor.fetchone()
def close(self):
self.conn.close()
if __name__ == '__main__': if __name__ == '__main__':
BlogArticle.from_dict({'title':'Заголовок','text':'Текст статьи'}) spyder = Spyder()
#for i in range(3): #spyder.init_db()
#scan(i) #spyder.scan('https://habr.com/ru/news/1046177/')
print(BlogArticle.count()) for _ in range(5):
for i in range(1): url = spyder.get_url()
print(BlogArticle.ls[i].to_dict()) print(url[0])
spyder.scan(url[0])
spyder.close()