Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- #
- # Author: yura_nn
- # License: GNU/GPL v3
- from bs4 import BeautifulSoup
- import hashlib
- import random
- import mysql.connector
- import time
- import math
- import re
- # Здесь нужно указать параметры подключения к базе данных.
- host = "localhost"
- database = "rutracker"
- user = "user_mysql"
- password = "password"
- phpbb_prefix = "rutrk_"
- # Путь к файлу xml.
- backup_xml = "/path/to/file.xml"
- # Начальный идентификатор темы. Таблица topics, поле topic_id.
- topic_id = 1
- # Начальный идентификатор поста. Таблица posts, поле post_id.
- post_id = 1
- # Счетчик постов с начальным значением. Таблица users, поле user_posts.
- count_post = 1
- # Идентификатор форума, в котором будут размещаться темы торрентов. Посмотреть
- # можно в таблице forums.
- forum_id = 2
- # Идентификатор пользователя форума phpbb3. Таблица users, поле user_id.
- user_id = 2
- # Имя пользователя форума phpbb3.
- topic_user = "user_phpBB3"
- def parse_torrent(line_xml):
- """ Функция парсит передаваемую строку. Выполняет нужные промежуточные
- действия. А затем формирует словарь, содержащий необходимые значения и
- возвращает его. """
- soup = BeautifulSoup(line_xml, "xml")
- torrent_all = soup.findAll("torrent")
- torrent_id = torrent_all[0]["id"]
- registred_at = torrent_all[0]["registred_at"]
- torrent_size = torrent_all[0]["size"]
- title = soup.title.string
- title = str(title)
- torrent_hash = torrent_all[1]["hash"]
- tracker_id = torrent_all[1]["tracker_id"]
- forum_id_old = soup.forum["id"]
- forum_name = soup.forum.string
- # Создание магнет ссылок.
- magnet_dht_only = create_magnet_dht(torrent_hash)
- magnet_rutracker = create_magnet_rutracker(torrent_hash)
- # Добавление bbcode code для магнет ссылок.
- magnet_dht_only = "[br]" + "Магнет ссылка (только DHT): " + '\n' + \
- "[code]" + magnet_dht_only + "[/code]" + '\n'
- magnet_rutracker = "[br]" + "Магнет ссылка (с bt*.t-ru.org): " + '\n' + \
- "[code]" + magnet_rutracker + "[/code]" + '\n'
- # Добавление bbcode url для торрент линка.
- hash_string = "[br]" + "Хеш раздачи:" + '\n' + "[code]" + \
- torrent_hash + "[/code]" + '\n'
- data_torrent = "Дата создания раздачи: " + registred_at + '\n'
- post_text = soup.content.string
- # Добавление даты создания раздачи, магнет ссылок, и значения хеша раздачи
- # прямо в пост.
- post_text = post_text + '\n' + magnet_rutracker
- post_text = post_text + magnet_dht_only
- post_text = post_text + hash_string
- post_text = post_text + data_torrent
- # Конвертирование текста поста в формат сообщений phpbb.
- post_text = convert_post_text(post_text)
- # В таблице базы данных нужно указать хеш-сумму сообщения.
- post_checksum = post_hash(post_text)
- # Идентификатор bbcode для поста.
- bbcode_uid = random_id()
- # Здесь добавляется значение текущего времени.
- time_post = math.floor(time.time())
- post_table_string = {
- "torrent_id": torrent_id,
- "title": title,
- "post_text": post_text,
- "post_checksum": post_checksum,
- "bbcode_uid": bbcode_uid,
- "time_post": time_post,
- "torrent_size": torrent_size,
- "tracker_id": tracker_id,
- "forum_id_old": forum_id_old,
- "forum_name": forum_name
- }
- return post_table_string
- def add_post_to_base(post_table_string):
- """ Функция заносит информацию о торренте в базу данных. """
- global topic_id
- global post_id
- global count_post
- # Соединение с базой данных.
- cnx = mysql.connector.connect(host=host,
- database=database,
- user=user,
- password=password)
- cursor = cnx.cursor()
- # Создание новой строки в таблице тем.
- part_query = "INSERT INTO " + phpbb_prefix + "topics "
- query = part_query + "(topic_id,forum_id,icon_id,topic_attachment," + \
- "topic_reported,topic_title,topic_poster,topic_time," + \
- "topic_time_limit,topic_views,topic_status,topic_type," + \
- "topic_first_post_id,topic_first_poster_name," + \
- "topic_first_poster_colour,topic_last_post_id," + \
- "topic_last_poster_id,topic_last_poster_name," + \
- "topic_last_poster_colour,topic_last_post_subject," + \
- "topic_last_post_time,topic_last_view_time,topic_moved_id," + \
- "topic_bumped,topic_bumper,poll_title,poll_start,poll_length," + \
- "poll_max_options,poll_last_vote,poll_vote_change," + \
- "topic_visibility,topic_delete_time,topic_delete_reason," + \
- "topic_delete_user,topic_posts_approved," + \
- "topic_posts_unapproved,topic_posts_softdeleted) " + \
- "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s," + \
- "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
- data = (topic_id, forum_id, 0, 0, 0, post_table_string["title"],
- user_id, post_table_string["time_post"], 0, 1, 0, 0, topic_id,
- topic_user, "AA0000", topic_id, user_id, topic_user, "AA0000",
- post_table_string["title"], post_table_string["time_post"],
- post_table_string["time_post"], 0, 0, 0, '', 0, 0, 1, 0, 0, 1, 0,
- '', 0, 1, 0, 0)
- cursor.execute(query, data)
- # Создание новой строки в таблице постов.
- part_query = "INSERT INTO " + phpbb_prefix + "posts "
- query = part_query + "(post_id,topic_id,forum_id,poster_id,icon_id," + \
- "poster_ip,post_time,post_reported,enable_bbcode," + \
- "enable_smilies,enable_magic_url,enable_sig,post_username," + \
- "post_subject,post_text,post_checksum,post_attachment, " + \
- "bbcode_bitfield,bbcode_uid,post_postcount,post_edit_time," + \
- "post_edit_reason,post_edit_user,post_edit_count," + \
- "post_edit_locked,post_visibility,post_delete_time," + \
- "post_delete_reason, post_delete_user) " + \
- "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s," + \
- "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
- data = (post_id, topic_id, forum_id, user_id, 0, "127.0.0.1",
- post_table_string["time_post"], 0, 1, 1, 1, 1, topic_user,
- post_table_string["title"], post_table_string["post_text"],
- post_table_string["post_checksum"], 0, '',
- post_table_string["bbcode_uid"], 1, 0, '', 0, 0, 0, 1, 0, '', 0)
- cursor.execute(query, data)
- # Создание новой строки в таблице topics_posted. Здесь при каждом новом
- # посте должна быть добавлена запись.
- part_query = "INSERT INTO " + phpbb_prefix + "topics_posted "
- query = part_query + "(user_id,topic_id,topic_posted) VALUES (%s,%s,%s)"
- data = (user_id, topic_id, 1)
- cursor.execute(query, data)
- # Изменение данных в таблице users.
- part_query = "UPDATE " + phpbb_prefix + "users "
- # Время последнего визита пользователя.
- query = part_query + "SET user_lastvisit = %s WHERE user_id = %s"
- data = (post_table_string["time_post"], user_id)
- cursor.execute(query, data)
- # Время последнего поста пользователя.
- query = part_query + "SET user_lastpost_time = %s WHERE user_id = %s"
- data = (post_table_string["time_post"], user_id)
- cursor.execute(query, data)
- # Количество постов пользователя.
- query = part_query + "SET user_posts = %s WHERE user_id = %s"
- data = (count_post, user_id)
- cursor.execute(query, data)
- # Изменение данных в таблице forums.
- part_query = "UPDATE " + phpbb_prefix + "forums "
- # ID последнего поста.
- query = part_query + "SET forum_last_post_id = %s WHERE forum_id = %s"
- data = (post_id, forum_id)
- cursor.execute(query, data)
- # Название последней темы.
- query = part_query + "SET forum_last_post_subject = %s WHERE forum_id = %s"
- data = (post_table_string["title"], forum_id)
- cursor.execute(query, data)
- # ID последнего пользователя, добавившего пост.
- query = part_query + "SET forum_last_poster_id = %s WHERE forum_id = %s"
- data = (user_id, forum_id)
- cursor.execute(query, data)
- # Ник последнего пользователя, добавившего пост.
- query = part_query + "SET forum_last_poster_name = %s WHERE forum_id = %s"
- data = (topic_user, forum_id)
- cursor.execute(query, data)
- # Время последнего поста.
- query = part_query + "SET forum_last_post_time = %s WHERE forum_id = %s"
- data = (post_table_string["time_post"], forum_id)
- cursor.execute(query, data)
- # Количество разрешенных постов.
- query = part_query + "SET forum_posts_approved = %s WHERE forum_id = %s"
- data = (count_post, forum_id)
- cursor.execute(query, data)
- # Количество разрешенных тем. Так как количество тем в данном случае равно
- # количеству постов, то в качестве значения добавляется счетчик постов.
- query = part_query + "SET forum_topics_approved = %s WHERE forum_id = %s"
- data = (count_post, forum_id)
- cursor.execute(query, data)
- # Изменение данных в таблице forums_track. Она содержит информацию о том,
- # что пользователь добавил сообщение в определенное время, для
- # определенного форума. В таблице одна строка, поэтому условия не нужны.
- part_query = "UPDATE " + phpbb_prefix + "forums_track "
- query = part_query + "SET user_id = %s"
- data = (user_id,)
- cursor.execute(query, data)
- query = part_query + "SET forum_id = %s"
- data = (forum_id,)
- cursor.execute(query, data)
- query = part_query + "SET mark_time = %s"
- data = (post_table_string["time_post"],)
- cursor.execute(query, data)
- cnx.commit()
- cursor.close()
- cnx.close()
- topic_id += 1
- post_id += 1
- count_post += 1
- def create_magnet_dht(torrent_hash):
- """ Функция создает только DHT магнет линк для раздачи рутрекера. """
- part_begin = "magnet:?xt=urn:btih:"
- magnet_link = part_begin + torrent_hash
- return magnet_link
- def create_magnet_rutracker(torrent_hash):
- """ Функция создает магнет линк для раздачи рутрекера, который имеет связь
- с различными адресами bt*.t-ru.org. """
- part_begin = "magnet:?xt=urn:btih:"
- part_end = [
- "&tr=http%3A%2F%2Fbt.t-ru.org%2Fann%3Fmagnet",
- "&tr=http%3A%2F%2Fbt2.t-ru.org%2Fann%3Fmagnet",
- "&tr=http%3A%2F%2Fbt3.t-ru.org%2Fann%3Fmagnet",
- "&tr=http%3A%2F%2Fbt4.t-ru.org%2Fann%3Fmagnet"
- ]
- number_element = random.randrange(0, 4, 1)
- magnet_link = part_begin + torrent_hash + part_end[number_element]
- return magnet_link
- def post_hash(string):
- """ Функция рассчитывает и возвращает хеш-сумму md5 переданной строки. """
- string = string.encode('utf-8')
- hash_string = hashlib.md5(string).hexdigest()
- return hash_string
- def random_id():
- """ Функция генерирует случайный цифро-буквенный идентификатор. """
- symbols_list = "qwertyuiopasdfghjklzxcvbnm1234567890"
- count_loop = random.randrange(1, 8, 1)
- # Произвольное увеличение заданной строки символов.
- for i in range(count_loop):
- symbols_list = symbols_list + symbols_list
- symbols_list = list(symbols_list)
- random.shuffle(symbols_list)
- destination_id = ''
- # Собственно создание идентификатора.
- for i in range(8):
- destination_id = destination_id + symbols_list[i]
- return destination_id
- def convert_post_text(post_text):
- """ В базе данных текст постов для phpbb лежит в своем собственном формате.
- Эта функция преобразует текст поста в необходимый формат. """
- # Пост сначала делится на отдельные строки для того, чтобы добавить в
- # каждую строку элемент <br/>. Если этого не сделать, то форматирование
- # поста поплывет.
- post_text = post_text.splitlines()
- destination_string = ''
- i = 0
- len_post_text = len(post_text)
- while i < len_post_text:
- new_str = post_text[i] + "<br/>" + '\n'
- del post_text[i]
- post_text.insert(i, new_str)
- destination_string = destination_string + post_text[i]
- i += 1
- # Дальше уже все действия выполняются с одной большой строкой.
- post_text = destination_string
- # Удаление элементов img.
- post_text = re.sub(
- r"(\[[iI][mM][gG]\][\d\s\w\W\n_]{1,}?\[/[iI][mM][gG]\])", '',
- post_text)
- post_text = re.sub(
- r"(\[[iI][mM][gG]=[rR][iI][gG][hH][tT]\][\d\s\w\W\n_]{1,}?\[/[iI][mM][gG]\])",
- '', post_text)
- post_text = re.sub(
- r"(\[[iI][mM][gG]=[lL][eE][fF][tT]\][\d\s\w\W\n_]{1,}?\[/[iI][mM][gG]\])",
- '', post_text)
- post_text = "<r>" + '\n' + post_text + "</r>"
- # Поиск list.
- if re.search(r"(\[[lL][iI][sS][tT]=?1?\])", post_text) is not None:
- # Создание списка соответствий существующих списков в теме.
- list_value = re.findall(
- r"(\[[lL][iI][sS][tT]=?1?\][\d\s\w\W\n_]{1,}?\[/[lL][iI][sS][tT]\])",
- post_text)
- list_value = check_list(list_value)
- for i in list_value:
- # Регулярное выражение для извлечения начального тега list.
- tag_begin = re.search(r"(\[[lL][iI][sS][tT]=?1?](<[br]/>)?)",
- i)
- tag_begin = tag_begin.group(0)
- tag_begin = re.sub(r"(\n?(<br/>)?)", '', tag_begin)
- tag_begin = "<LIST><s>" + tag_begin + "</s>" + "<br/>" + '\n'
- tag_end = "<e>[/list]</e></LIST>"
- # Регулярное выражение для извлечения элементов списка.
- list_elements = re.findall(r"(\[\*\].{1,})", i)
- list_elements = check_list(list_elements)
- destination_value = ''
- for n in list_elements:
- new_str = re.sub(r"(\n?(<br/>)?)", '', n)
- new_str = re.sub(r"(\[\*\])", '', new_str)
- new_str = "<LI><s>[*]</s>" + new_str + "</LI>" + '\n'
- destination_value = destination_value + new_str
- destination_value = re.sub(r"(\[/[lL][iI][sS][tT]\])", '',
- destination_value)
- destination_value = tag_begin + destination_value + tag_end
- post_text = post_text.replace(i, destination_value)
- # Поиск font.
- if re.search(r"(\[[fF][oO][nN][tT]=)", post_text) is not None:
- list_value = re.findall(
- r"(\[[fF][oO][nN][tT]=[\'\"]?[\'\"]?[a-zA-Z0-9^$\(\),.\s\-_:\?/=#&!\*<>+]{1,}[\'\"]?[\'\"]?\])",
- post_text)
- list_value = check_list(list_value)
- for i in list_value:
- destination_value = re.sub(r"(\[[fF][oO][nN][tT]=[\'\"]?)",
- '', i)
- destination_value = re.sub(r"([\'\"]?\])", '', destination_value)
- destination_value = '<FONT font="' + destination_value \
- + '"><s>' + i + "</s>"
- post_text = post_text.replace(i, destination_value)
- # Поиск "color=".
- if re.search(r"(\[[cC][oO][lL][oO][rR]=)", post_text) is not None:
- list_value = re.findall(
- r"(\[[cC][oO][lL][oO][rR]=[\'\"]?[#0-9a-zA-Z]{1,}[\'\"]?\])",
- post_text)
- list_value = check_list(list_value)
- for i in list_value:
- destination_value = re.sub(r"(\[[cC][oO][lL][oO][rR]=[\'\"]?)",
- '', i)
- destination_value = re.sub(r"([\'\"]?\])", '', destination_value)
- destination_value = '<COLOR color="' + destination_value \
- + '"><s>' + i + "</s>"
- post_text = post_text.replace(i, destination_value)
- # Поиск "size=".
- if re.search(r"(\[[sS][iI][zZ][eE]=)", post_text) is not None:
- list_value = re.findall(
- r"(\[[sS][iI][zZ][eE]=[\"\']?[0-9]{,3}[\"\']?\])", post_text)
- list_value = check_list(list_value)
- for i in list_value:
- destination_value = re.sub(r"(\[[sS][iI][zZ][eE]=[\'\"]?)", '', i)
- destination_value = re.sub(r"([\'\"]?\])", '', destination_value)
- destination_value = '<SIZE size="' + destination_value + \
- '"><s>' + i + "</s>"
- post_text = post_text.replace(i, destination_value)
- # Тег "url=".
- if re.search(r"(\[[uU][rR][lL]=)", post_text) is not None:
- list_value = re.findall(
- r"(\[[uU][rR][lL]=[\']?[-a-zA-Zа-яА-ЯёЁ0-9\.\/\:\?=#&@;_%\(\),+!\*<>]{1,}[\']?\])",
- post_text)
- list_value = check_list(list_value)
- for i in list_value:
- destination_value = re.sub(r"(\[[uU][rR][lL]=[\'\"]?)", '', i)
- destination_value = re.sub(r"([\'\"]?\])", '', destination_value)
- destination_value = '<URL url="' + destination_value + '"><s>' + \
- i + "</s>"
- post_text = post_text.replace(i, destination_value)
- # Тег spoiler=".
- if re.search(r"(\[[sS][pP][oO][iI][lL][eE][rR]=)",
- post_text) is not None:
- list_value = re.findall(
- r"(\[[sS][pP][oO][iI][lL][eE][rR]=[\"].{1,}[\"]\])",
- post_text)
- list_value = check_list(list_value)
- for i in list_value:
- destination_value = re.sub(r"(\[[sS][pP][oO][iI][lL][eE][rR]=[\"])",
- '', i)
- destination_value = re.sub(r"([\"]\])", '', destination_value)
- destination_value = "<SPOILER spoiler=" + '"' + \
- destination_value + '"' + \
- '><s>' + '[spoiler="' + \
- destination_value + '"' + \
- ']' + "</s>"
- post_text = post_text.replace(i, destination_value)
- # Тег align=".
- if re.search(r"(\[[aA][lL][iI][gG][nN]=)", post_text) is not None:
- list_value = re.findall(
- r"(\[[aA][lL][iI][gG][nN]=[\'\"]?[a-zA-Z]{1,}[\'\"]?\])",
- post_text)
- list_value = check_list(list_value)
- for i in list_value:
- destination_value = re.sub(r"(\[[aA][lL][iI][gG][nN]=[\'\"]?)",
- '', i)
- destination_value = re.sub(r"([\'\"]?\])", '', destination_value)
- destination_value = '<ALIGN align="' + destination_value + \
- '"><s>[align=' \
- + destination_value + \
- "]</s>"
- post_text = post_text.replace(i, destination_value)
- # Элемент quote.
- if re.search(r"(\[[qQ][uU][oO][tT][eE]\])", post_text) is not None:
- post_text = re.sub(r"(\[[qQ][uU][oO][tT][eE]\])",
- "<QUOTE><s>[quote]</s>", post_text)
- if re.search(r"(\[/[qQ][uU][oO][tT][eE]\])", post_text) is not None:
- post_text = re.sub(r"(\[/[qQ][uU][oO][tT][eE]\])",
- "<e>[/quote]</e></QUOTE>", post_text)
- # Элемент code.
- if re.search(r"(\[[cC][oO][dD][eE]\])", post_text) is not None:
- post_text = re.sub(r"(\[[cC][oO][dD][eE]\])",
- "<CODE><s>[code]</s>", post_text)
- if re.search(r"(\[/[cC][oO][dD][eE]\])", post_text) is not None:
- post_text = re.sub(r"(\[/[cC][oO][dD][eE]\])",
- "<e>[/code]</e></CODE>", post_text)
- # Элемент pre.
- if re.search(r"(\[[pP][rR][eE]\])", post_text) is not None:
- post_text = re.sub(r"(\[[pP][rR][eE]\])",
- "<PRE><s>[pre]</s>", post_text)
- if re.search(r"(\[/[pP][rR][eE]\])", post_text) is not None:
- post_text = re.sub(r"(\[/[pP][rR][eE]\])",
- "<e>[/pre]</e></PRE>", post_text)
- # Элемент b.
- if re.search(r"(\[[bB]\])", post_text) is not None:
- post_text = re.sub(r"(\[[bB]\])", "<B><s>[b]</s>", post_text)
- if re.search(r"(\[/[bB]\])", post_text) is not None:
- post_text = re.sub(r"(\[/[bB]\])", "<e>[/b]</e></B>", post_text)
- # Элемент i.
- if re.search(r"(\[[iI]\])", post_text) is not None:
- post_text = re.sub(r"(\[[iI]\])", "<I><s>[i]</s>", post_text)
- if re.search(r"(\[/[iI]\])", post_text) is not None:
- post_text = re.sub(r"(\[/[iI]\])", "<e>[/i]</e></I>", post_text)
- # Элемент u.
- if re.search(r"(\[[uU]\])", post_text) is not None:
- post_text = re.sub(r"(\[[uU]\])", "<U><s>[u]</s>", post_text)
- if re.search(r"(\[/[uU]\])", post_text) is not None:
- post_text = re.sub(r"(\[/[uU]\])", "<e>[/u]</e></U>", post_text)
- # Элемент br.
- if re.search(r"(\[[bB][rR]\])", post_text) is not None:
- post_text = re.sub(r"(\[[bB][rR]\])",
- "<BR><s>[br]</s><e>[/br]</e></BR>", post_text)
- if re.search(r"(\[[hH][rR]\])", post_text) is not None:
- post_text = re.sub(r"(\[[hH][rR]\])",
- "<HR><s>[hr]</s><e>[/hr]</e></HR>", post_text)
- # Для спойлера без описания.
- if re.search(r"(\[[sS][pP][oO][iI][lL][eE][rR]\])", post_text) \
- is not None:
- post_text = re.sub(r"(\[[sS][pP][oO][iI][lL][eE][rR]\])",
- "<SPOILER><s>[spoiler]</s>", post_text)
- if re.search(r"(\[/[sS][pP][oO][iI][lL][eE][rR]\])", post_text) \
- is not None:
- post_text = re.sub(r"(\[/[sS][pP][oO][iI][lL][eE][rR]\])",
- "<e>[/spoiler]</e></SPOILER>", post_text)
- # Для завершающего тега size.
- if re.search(r"(\[/[sS][iI][zZ][eE]\])", post_text) is not None:
- post_text = re.sub(r"(\[/[sS][iI][zZ][eE]\])",
- "<e>[/size]</e></SIZE>", post_text)
- # Для завершающего тега spoiler.
- if re.search(r"(\[/[cC][oO][lL][oO][rR]\])", post_text) is not None:
- post_text = re.sub(r"(\[/[cC][oO][lL][oO][rR]\])",
- "<e>[/color]</e></COLOR>", post_text)
- # Для завершающего тега url.
- if re.search(r"(\[/[uU][rR][lL]\])", post_text) is not None:
- post_text = re.sub(r"(\[/[uU][rR][lL]\])",
- "<e>[/url]</e></URL>", post_text)
- # Для завершающего тега align.
- if re.search(r"(\[/[aA][lL][iI][gG][nN]\])", post_text) is not None:
- post_text = re.sub(r"(\[/[aA][lL][iI][gG][nN]\])",
- "<e>[/align]</e></ALIGN>", post_text)
- # Для завершающего тега font.
- if re.search(r"(\[/[fF][oO][nN][tT]\])", post_text) is not None:
- post_text = re.sub(r"(\[/[fF][oO][nN][tT]\])",
- "<e>[/font]</e></FONT>", post_text)
- return post_text
- def check_list(list_value):
- """ Когда используется список совпадения для замены тегов, нельзя, чтобы в
- нем были повторяющиеся пункты, иначе замена может произойти в уже
- замененном. Эта функция удаляет повторения. """
- current_list = []
- n = 0
- len_list_value = len(list_value)
- while n < len_list_value:
- flag = False
- for i in current_list:
- if list_value[n] == i:
- flag = True
- if flag is False:
- current_list.append(list_value[n])
- n += 1
- return current_list
- def main():
- # Каждая запись с торрентом преобразуется в свой маленький xml файл,
- # который парсится дальше уже с помощью BeautifulSoup.
- first_xml_string = '<?xml version="1.0" encoding="UTF-8"?>' + '\n'
- other_xml_string = "<torrents>" + '\n'
- last_xml_string = "</torrents>" + '\n'
- line_xml = ''
- fd = open(backup_xml, "r")
- for line in fd:
- if line.find("<torrent id") != -1:
- line_xml = first_xml_string + other_xml_string
- line_xml = line_xml + line
- if line.find("</torrent") != -1:
- line_xml = line_xml + last_xml_string
- post_table_string = parse_torrent(line_xml)
- add_post_to_base(post_table_string)
- fd.close()
- if __name__ == "__main__":
- main()
Add Comment
Please, Sign In to add comment