-
Notifications
You must be signed in to change notification settings - Fork 0
upd #1
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
Open
spqrlatin
wants to merge
24
commits into
main
Choose a base branch
from
init
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
upd #1
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
9d95dca
upd
spqrlatin 5b7f0b4
upd
spqrlatin 148ffb9
upd
spqrlatin 93c436a
upd
spqrlatin e30c344
upd
spqrlatin fe8cd87
add rows for current_users
spqrlatin 74fa5ce
add rows for current_users
spqrlatin 482cf34
upd refactoring
spqrlatin 5fc0e30
upd clean up
spqrlatin 07915e5
upd dry refactoring
spqrlatin d7a2f85
upd dry code
spqrlatin 3eac2b8
add ER dig
spqrlatin 259be18
upd
spqrlatin 1c80ee0
upd
spqrlatin 1566f69
add DB, refactoring
spqrlatin 4ad6236
fix
spqrlatin fba027b
few changes in html
spqrlatin 46fb7dc
upd
khramov86 8bebab5
upd
khramov86 f9b556a
mvp done
spqrlatin 54e1104
upd ref DRY
spqrlatin 3a3b365
upd todo
spqrlatin e925025
Merge branch 'init' of github.com:spqrlatin/projectparser into init
khramov86 0eab110
upd
khramov86 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| # projectparser | ||
|
|
||
|
|
||
| ## Подготовка окружения | ||
|
|
||
| ``` | ||
| pip install -r req.txt | ||
| ``` | ||
|
|
||
| ## Наполнение данных | ||
|
|
||
| * Запуск парсинга | ||
| ``` | ||
| python parserweb/parser.py | ||
| ``` | ||
| * Наполнение БД | ||
| ``` | ||
| python populate_db.py | ||
| ``` | ||
| * Запуск приложения | ||
| ``` | ||
| ./run.sh | ||
| ``` | ||
| ## Модель данных | ||
|
|
||
|  | ||
|
|
||
| Link | ||
|
|
||
| https://dbdesigner.page.link/wCPjHn8Gwk7iNKeEA | ||
|
|
||
|
|
||
|
|
||
| ## TODO | ||
|
|
||
| [TODO](TODO.md) | ||
|
|
||
| ## Типовые проблемы | ||
|
|
||
| ### Проблемы с импортом | ||
|
|
||
| если не проходит импорт, например | ||
| ``` | ||
| ModuleNotFoundError: No module named 'parser_core' | ||
| ``` | ||
| Необходимо проверить: | ||
| ``` | ||
| echo $PYTHONPATH | ||
| ``` | ||
| если переменная пустая, то в корне проекта выполнить: | ||
| ``` | ||
| export PYTHONPATH=$PWD | ||
| ``` |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| # Что нужно сделать | ||
|
|
||
| ## MVP | ||
| - [x] получить данные | ||
| - [x] парсинг первой страницы | ||
| - [x] парсинг данных пользователя | ||
| - [x] рефакторинг кода для 'недействующих пользователей' | ||
| - [x] рефакторинг DRY | ||
| - [x] спроектировать базу | ||
| - [x] вставить данные в базу | ||
| - [x] вывод базы данных в вебе | ||
| - [x] фильтр по полю статуса агентов | ||
| - [x] статус выгрузки (progress bar) | ||
| ## Improvment | ||
| - [ ] парсинг с пагинацией | ||
| - [ ] реализовать логирование выгрузки данных | ||
| - [ ] асинхронные запросы к API |
Empty file.
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| from flask_sqlalchemy import SQLAlchemy | ||
|
|
||
|
|
||
| db = SQLAlchemy() | ||
|
|
||
| """ | ||
| class Ensurance(db.Model): | ||
| id = db.Column(db.Integer, primary_key=True) | ||
| ensurance_org=db.Column(db.String, nullable=True) | ||
| """ | ||
|
|
||
| class Rsodata(db.Model): | ||
| id = db.Column(db.Integer, primary_key=True) | ||
| reestr_number = db.Column(db.Text) | ||
| satisfied = db.Column(db.String) | ||
| excluded = db.Column(db.Text, nullable=True) | ||
| stopped = db.Column(db.Text, nullable=True) | ||
| grade = db.Column(db.String, nullable=True) | ||
| lfm = db.Column(db.String, nullable=True) | ||
| compensation = db.Column(db.String, nullable=True) | ||
| experience = db.Column(db.String, nullable=True) | ||
| contacts = db.Column(db.Text, nullable=True) | ||
| url = db.Column(db.String, unique=True, nullable=True) | ||
| ensurance=db.Column(db.String, nullable=True) | ||
| def __repr__(self): | ||
| return '<Person info {} {} {} {}>'.format(self.reestr_number, self.satisfied ,self.excluded ,self.url) | ||
|
|
||
| """ | ||
| class User(db.Model): | ||
| id = db.Column(db.Integer, primary_key=True) | ||
| #firstname = db.Column(db.String, nullable=True) | ||
| #lastname = db.Column(db.String, nullable=True) | ||
| #middlename = db.Column(db.String, nullable=True) | ||
| lfm = db.Column(db.String, nullable=True) | ||
| compensation = db.Column(db.String, nullabale=True) | ||
| experience = db.Column(db.String, nullabale=True) | ||
| contacts = db.Column(db.Text, nullable=True) | ||
| #ensurance_id = db.Column(db.Integer, unique=True) | ||
| #rso_id = db.Column(db.Boolean, nullabale=True) | ||
| url = db.Column(db.String, unique=True, nullable=True) | ||
| """ | ||
|
|
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| CREATE TABLE Users ( | ||
| id integer PRIMARY KEY AUTOINCREMENT, | ||
| firstname varchar PRIMARY KEY AUTOINCREMENT, | ||
| lastname varchar PRIMARY KEY AUTOINCREMENT, | ||
| middlename varchar PRIMARY KEY AUTOINCREMENT, | ||
| compensation varchar, | ||
| experience integer, | ||
| contacts varchar, | ||
| ensurance_id integer, | ||
| rso_id blob, | ||
| url varchar | ||
| ); | ||
|
|
||
| CREATE TABLE rsodata ( | ||
| id integer PRIMARY KEY AUTOINCREMENT, | ||
| reestr_number integer, | ||
| satisfied blob, | ||
| excluded varchar, | ||
| stopped varchar, | ||
| grade varchar | ||
| ); | ||
|
|
||
| CREATE TABLE ensurance ( | ||
| id integer PRIMARY KEY AUTOINCREMENT, | ||
| ensurance_org varchar PRIMARY KEY AUTOINCREMENT | ||
| ); |
Empty file.
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| from bs4 import BeautifulSoup | ||
| import requests | ||
| import re | ||
| from pprint import pprint | ||
|
|
||
| headers = {} | ||
|
|
||
| def get_user_info(url, headers): | ||
| response = requests.get(url, headers=headers) | ||
| return response.text | ||
|
|
||
| def parse_table(soup): | ||
| try: | ||
| data = soup.find('div', class_ = 'reestr').find_all('table') | ||
| temp_dict = {} | ||
| for row in data: | ||
| # print(row) | ||
| key = row.find('td').text.strip() | ||
| try: | ||
| value = ' '.join(row.find('td', class_ = 'posrel').get_text(strip=True, separator='\n').split('\n')[:-1]).strip() | ||
| except: | ||
| value = None | ||
| temp_dict[key] = value | ||
| return temp_dict | ||
| except: | ||
| return {} | ||
|
|
||
| def get_person(soup): | ||
| temp_dict = parse_table(soup) | ||
| satisfied = temp_dict.get('Соответствие условиям членства в СРО, предусмотренным законодательством Российской Федерации и (или) внутренними документами СРО') | ||
| stopped = temp_dict.get('Приостановка права осуществления оценочной деятельности') | ||
| grade = temp_dict.get('Степень членства') | ||
| ensurance = temp_dict.get('Страхование деятельности') | ||
| return { | ||
| 'bilet': temp_dict.get('Членский билет'), | ||
| 'grade': grade if grade else 'Не является членом', | ||
| 'satisfied': satisfied if satisfied else 'Не соответствует', | ||
| 'reestr_number': temp_dict.get('Номер в Реестре РОО'), | ||
| 'contacts': temp_dict.get('Контакты'), | ||
| 'organization': temp_dict.get('Организация (место работы)'), | ||
| 'experience': temp_dict.get('Стаж'), | ||
| 'ensurance': ensurance if ensurance else 'Страховая организация отсутствует', | ||
| 'compensation': temp_dict.get('Компенсационный фонд'), | ||
| 'excluded': temp_dict.get('Исключен', 'Действующий'), | ||
| 'stopped': stopped if stopped else 'Не приостановлено' | ||
| } | ||
|
|
||
|
|
||
| def cleanup_changed(content, idx): | ||
| if idx > len(content): | ||
| return None | ||
| try: | ||
| return ' '.join(content[idx].get_text(strip=True, separator='\n').split('\n')[:-1]) | ||
| except: | ||
| return None | ||
|
|
||
| def parse_user_info(content, url): | ||
| soup = BeautifulSoup(content, "html.parser") | ||
| try: | ||
| lfm = soup.find("h3").text | ||
| except AttributeError: | ||
| lfm = None | ||
| try: | ||
| date_and_city_of_birth = soup.find("div", class_="reestr").find('p').text.strip() | ||
| city_of_birth = date_and_city_of_birth.split(',')[1].strip() | ||
| date_of_birth = date_and_city_of_birth.split(',')[0].split('-')[1].strip() | ||
| except: | ||
| city_of_birth = None | ||
| date_of_birth = None | ||
| try: | ||
| status = soup.find("table", class_="top").find('td').text.strip() | ||
| except: | ||
| status = "Действующий" | ||
|
|
||
| expanded_dict = get_person(soup) | ||
| return { | ||
| 'lfm': lfm, | ||
| 'birth_date': date_of_birth, | ||
| 'birth_city': city_of_birth, | ||
| 'status': status, | ||
| 'url': url, | ||
| **expanded_dict | ||
| } | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| from parserweb.parser import headers | ||
| url = 'http://sroroo.ru/about/reestr/379972/' | ||
| #url = 'http://sroroo.ru/about/reestr/806693/' | ||
| # with open("index.html", "w") as file: | ||
| # data = get_user_info(url, headers) | ||
| # file.write(data) | ||
| with open('index.html', encoding='utf-8') as file: | ||
| data = file.read() | ||
| parsed_data = parse_user_info(data, url) | ||
| pprint(parsed_data) | ||
|
|
||
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| from flask import Flask, render_template,Blueprint | ||
| from db.model import Rsodata | ||
| from db.model import db | ||
| from parserweb.parser import return_parsed_data | ||
| rso_data_column_dict = { | ||
| 'id': "Порядковый номер", | ||
| 'reestr_number': "Номер в реестре", | ||
| 'satisfied': "Соответствует ли", | ||
| 'excluded': "Является ли агентом", | ||
| 'stopped': "Прекращено ли членство", | ||
| 'grade': "Степень членства", | ||
| 'contacts': "Контакты", | ||
| 'organization': "Страховые компании", | ||
| 'experience': "Стаж", | ||
| 'ensurance': "Страховщик", | ||
| 'compensation': "Компенсационный фонд", | ||
| 'lfm': "ФИО", | ||
| 'url': "ссылка", | ||
| } | ||
| displayed_col = ['lfm', 'grade', 'excluded', 'url'] | ||
|
|
||
| def create_app(): | ||
| columns = Rsodata.__table__.columns.keys() | ||
| app = Flask(__name__) | ||
| app.config.from_pyfile('config.py') | ||
| db.init_app(app) | ||
| @app.route('/') | ||
| def index(): | ||
| title = "Информация по агентам" | ||
| active_agents = ['lfm', 'grade', 'exluded', 'url'] | ||
| agent_list = Rsodata.query.all() | ||
| # print(columns) | ||
| #print(agent_list) | ||
| #print("Everything done") | ||
| #print(title, weather, news_list) | ||
| return render_template('info.html', page_title=title, | ||
| agent_list=agent_list, columns=columns, | ||
| rso_data_column_dict=rso_data_column_dict, | ||
| displayed_col=displayed_col) | ||
| # return render_template('debug.html') | ||
| @app.route('/active') | ||
| def filtered(): | ||
| title = "Информация активным по агентам" | ||
| agent_list = Rsodata.query.filter(Rsodata.grade.in_(['Действительный член РОО'])).all() | ||
|
|
||
| # print(columns) | ||
| #print(agent_list) | ||
| #print("Everything done") | ||
| #print(title, weather, news_list) | ||
| return render_template('info.html', page_title=title, | ||
| agent_list=agent_list, columns=columns, | ||
| rso_data_column_dict=rso_data_column_dict, | ||
| displayed_col=displayed_col) | ||
|
|
||
| # @app.route('/') | ||
| # def index(): | ||
| # title = "Информация по агентам оценки" | ||
| # person_list = return_parsed_data() | ||
| # return render_template('index.html', page_title=title, person_list=person_list) | ||
|
|
||
| # blueprint = Blueprint('news', __name__) | ||
|
|
||
|
|
||
|
|
||
| return app |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| import os | ||
|
|
||
| basedir = os.path.abspath(os.path.dirname(__file__)) | ||
| # print(basedir) | ||
| SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, '..' , 'projectparser.db') | ||
| BASE_URL = 'http://sroroo.ru' | ||
| SQLALCHEMY_TRACK_MODIFICATIONS = False |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Возможно имеет смысл сделать парсинг этих полей так же через parse_table для единообразия.