Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Date enhancement #71

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
# created by virtualenv automatically
*
venv/*
result/*
settings.ini
database.db
downloaded_files/*
__pycache__/*

settings.ini
54 changes: 51 additions & 3 deletions parser_cls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from datetime import datetime, timedelta
import random
import sys
import threading
import time
import re
Expand Down Expand Up @@ -190,13 +192,57 @@ def __pretty_log(data):
name = data.get("name", "-")
id_ = data.get("id", "-")
seller_name = data.get("seller_name")
public_date = data.get("date_public")
short_url = f"https://avito.ru/{id_}"
message = (
f"{price}\n{name}\n{short_url}\n"
+ (f"Продавец: {seller_name}\n" if seller_name else "")
+ (f"Дата: {public_date}\n" if public_date else "")
)
logger.success(message)

@staticmethod
def __datepublic_to_datestamp(date_of_public: str)->str:
"""преобразует формат авито в понятный для Excel формат.
Args:
date_of_public (str): date with two diff format
Returns:
str: отображение вида: 08.12 11:20
"""
months = {
'января': '01',
'февраля': '02',
'марта': '03',
'апреля': '04',
'мая': '05',
'июня': '06',
'июля': '07',
'августа': '08',
'сентября': '09',
'октября': '10',
'ноября': '11',
'декабря': '12',
}
match (date_of_public.split(' ')):
case public_day, public_month, public_time:
choisen_month = months.get(public_month) or '_'
# здесь формат "9 ноября в 16:25"
return (f'{public_day.zfill(2)}.{choisen_month} '
f'{public_time}')
# здесь формат 'вчера в 11:19'
case 'вчера', public_time:
yerstaday_date = datetime.now()-timedelta(days=1)
return (f'{yerstaday_date.day:02}.{yerstaday_date.month:02} '
f'{public_time}')
case 'сегодня', public_time:
return (f'{datetime.now().day:02}.{datetime.now().month:02} '
f'{public_time}')
case _:
logger.warning('Формат даты со страницы неверный - %s',
date_of_public)
return date_of_public


def __parse_full_page(self, data: dict) -> dict:
"""Парсит для доп. информации открытое объявление"""
self.driver.uc_open(data.get("url"))
Expand Down Expand Up @@ -229,9 +275,8 @@ def __parse_full_page(self, data: dict) -> dict:
"""Дата публикации"""
if self.driver.find_elements(LocatorAvito.DATE_PUBLIC[1], by="css selector"):
date_public = self.driver.find_element(LocatorAvito.DATE_PUBLIC[1], by="css selector").text
if "· " in date_public:
date_public = date_public.replace("· ", '')
data["date_public"] = date_public
date_public = date_public.replace("· ", '').replace(' в ', ' ')
data["date_public"] = self.__datepublic_to_datestamp(date_public)

"""Имя продавца"""
if self.driver.find_elements(LocatorAvito.SELLER_NAME[1], by="css selector"):
Expand Down Expand Up @@ -367,3 +412,6 @@ def change_ip(self) -> bool:
'Если ошибка повторится несколько раз - перезапустите скрипт.'
'Если и это не поможет - значит что-то сломалось')
time.sleep(30)
except KeyboardInterrupt:
logger.info('Выход по требованию пользователя')
sys.exit(0)
79 changes: 75 additions & 4 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,78 @@
anyio==4.7.0
attrs==24.2.0
beautifulsoup4==4.12.3
loguru==0.7.0
behave==1.2.6
certifi==2024.12.14
cffi==1.17.1
chardet==5.2.0
charset-normalizer==3.4.0
click==8.1.7
colorama==0.4.6
cssselect==1.2.0
et_xmlfile==2.0.0
exceptiongroup==1.2.2
execnet==2.1.1
fasteners==0.19
filelock==3.16.1
flet==0.25.2
flet-desktop==0.25.2
h11==0.14.0
httpcore==1.0.7
httpx==0.28.1
idna==3.10
iniconfig==2.0.0
Jinja2==3.1.4
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
loguru==0.7.3
markdown-it-py==3.0.0
MarkupSafe==3.0.2
mdurl==0.1.2
mycdp==1.1.0
notifiers==1.3.3
python-dotenv==1.0.1
oauthlib==3.2.2
openpyxl==3.1.5
outcome==1.3.0.post0
packaging==24.2
parameterized==0.9.0
parse==1.20.2
parse_type==0.6.4
pdbp==1.6.1
platformdirs==4.3.6
pluggy==1.5.0
pycparser==2.22
Pygments==2.18.0
pynose==1.5.3
pyotp==2.9.0
pyreadline3==3.5.4
PySocks==1.7.1
pytest==8.3.4
pytest-html==4.0.2
pytest-metadata==3.1.1
pytest-ordering==0.6
pytest-rerunfailures==15.0
pytest-xdist==3.6.1
PyYAML==6.0.2
referencing==0.35.1
repath==0.9.0
requests==2.32.3
seleniumbase
openpyxl
rich==13.9.4
rpds-py==0.22.3
sbvirtualdisplay==1.3.1
selenium==4.27.1
seleniumbase==4.33.11
setuptools==75.6.0
six==1.17.0
sniffio==1.3.1
sortedcontainers==2.4.0
soupsieve==2.6
tabcompleter==1.4.0
trio==0.27.0
trio-websocket==0.11.1
typing_extensions==4.12.2
urllib3==2.2.3
websocket-client==1.8.0
websockets==14.1
wheel==0.45.1
win32_setctime==1.2.0
wsproto==1.2.0
19 changes: 0 additions & 19 deletions settings.ini

This file was deleted.