සියලුම Habr එක දත්ත ගබඩාවක

සුභ සන්ධ්යාවක්. ඒක ලියලා අවුරුදු 2ක් වෙනවා. පසුගිය ලිපිය Habr විග්‍රහ කිරීම ගැන, සහ සමහර කරුණු වෙනස් වී ඇත.

මට Habr පිටපතක් ලබා ගැනීමට අවශ්‍ය වූ විට, කතුවරුන්ගේ සියලුම අන්තර්ගතයන් දත්ත ගබඩාවට සුරැකිය හැකි විග්‍රහයක් ලිවීමට මම තීරණය කළෙමි. එය සිදු වූ ආකාරය සහ මා මුහුණ දුන් දෝෂ මොනවාද - ඔබට කප්පාදුව යටතේ කියවිය හැකිය.

TLDR- දත්ත සමුදා සබැඳිය

විග්‍රහයේ පළමු අනුවාදය. එක ත්‍රෙඩ් එකක්, ප්‍රශ්න ගොඩක්

ආරම්භ කිරීම සඳහා, බාගත කළ වහාම ලිපිය විග්‍රහ කර දත්ත ගබඩාවේ තබන ස්ක්‍රිප්ට් මූලාකෘතියක් සෑදීමට මම තීරණය කළෙමි. දෙපාරක් හිතන්නේ නැතුව මම sqlite3 පාවිච්චි කළා, මොකද. එය අඩු ශ්‍රම තීව්‍රතාවයක් විය: දේශීය සේවාදායකයක් තිබීම අවශ්‍ය නොවේ, සාදන ලද-පෙනුණු-මකා දැමූ සහ එවැනි දේවල්.

one_thread.py

from bs4 import BeautifulSoup
import sqlite3
import requests
from datetime import datetime

def main(min, max):
    conn = sqlite3.connect('habr.db')
    c = conn.cursor()
    c.execute('PRAGMA encoding = "UTF-8"')
    c.execute("CREATE TABLE IF NOT EXISTS habr(id INT, author VARCHAR(255), title VARCHAR(255), content  TEXT, tags TEXT)")

    start_time = datetime.now()
    c.execute("begin")
    for i in range(min, max):
        url = "https://m.habr.com/post/{}".format(i)
        try:
            r = requests.get(url)
        except:
            with open("req_errors.txt") as file:
                file.write(i)
            continue
        if(r.status_code != 200):
            print("{} - {}".format(i, r.status_code))
            continue

        html_doc = r.text
        soup = BeautifulSoup(html_doc, 'html.parser')

        try:
            author = soup.find(class_="tm-user-info__username").get_text()
            content = soup.find(id="post-content-body")
            content = str(content)
            title = soup.find(class_="tm-article-title__text").get_text()
            tags = soup.find(class_="tm-article__tags").get_text()
            tags = tags[5:]
        except:
            author,title,tags = "Error", "Error {}".format(r.status_code), "Error"
            content = "При парсинге этой странице произошла ошибка."

        c.execute('INSERT INTO habr VALUES (?, ?, ?, ?, ?)', (i, author, title, content, tags))
        print(i)
    c.execute("commit")
    print(datetime.now() - start_time)

main(1, 490406)

සෑම දෙයක්ම සම්භාව්යයි - අපි ලස්සන සුප් භාවිතා කරමු, ඉල්ලීම් සහ ඉක්මන් මූලාකෘතියක් සූදානම්. ඒ නිකම්…

  • පේජ් ඩවුන්ලෝඩ් එක ත්‍රෙඩ් එකක

  • ඔබ ස්ක්‍රිප්ට් ක්‍රියාත්මක කිරීමට බාධා කළහොත්, සම්පූර්ණ දත්ත සමුදායම කොතැනකවත් නොයනු ඇත. සියල්ලට පසු, කැපවීම සිදු කරනු ලබන්නේ සියලු විග්‍රහ කිරීමෙන් පසුව පමණි.
    ඇත්ත වශයෙන්ම, එක් එක් ඇතුළත් කිරීමෙන් පසු ඔබට දත්ත සමුදායේ වෙනස්කම් සිදු කළ හැකිය, නමුත් පසුව ස්ක්‍රිප්ට් ක්‍රියාත්මක කිරීමේ කාලය සැලකිය යුතු ලෙස වැඩි වනු ඇත.

  • පළමු ලිපි 100 විග්‍රහ කිරීමට මට පැය 000ක් ගත විය.

ඊළඟට මම පරිශීලකයාගේ ලිපිය සොයා ගන්නෙමි ඒකාබද්ධ, මම කියවා මෙම ක්‍රියාවලිය වේගවත් කිරීම සඳහා ජීවිත හැක් කිහිපයක් සොයා ගත්තා:

  • බහු නූල් භාවිතා කිරීම විටින් විට බාගත කිරීම වේගවත් කරයි.
  • ඔබට habr හි සම්පූර්ණ අනුවාදය නොව එහි ජංගම අනුවාදය ලබා ගත හැකිය.
    උදාහරණයක් ලෙස, ඩෙස්ක්ටොප් අනුවාදයේ ඒකාබද්ධ ලිපියක් බර 378 KB නම්, ජංගම අනුවාදයේ එය දැනටමත් 126 KB වේ.

දෙවන අනුවාදය. බොහෝ නූල්, Habr වෙතින් තාවකාලික තහනම

මම python හි multithreading මාතෘකාව මත අන්තර්ජාලය පිරික්සූ විට, මම multiprocessing.dummy සමඟ ඇති සරලම විකල්පය තෝරා ගත්තෙමි, බහු නූල් සමග ගැටලු මතු වන බව මම දුටුවෙමි.

SQLite3 ට නූල් එකකට වඩා වැඩ කිරීමට අවශ්‍ය නැත.
ස්ථාවර check_same_thread=False, නමුත් මෙම දෝෂය එකම එක නොවේ, දත්ත සමුදායට ඇතුළු කිරීමට උත්සාහ කරන විට, සමහර විට මට විසඳා ගත නොහැකි දෝෂ ඇති වේ.

එබැවින්, ලිපි ලේඛන සෘජුවම දත්ත ගබඩාවට ඇතුළු කිරීම අත්හැර දැමීමට මම තීරණය කරන අතර, ඒකාබද්ධ විසඳුම මතක තබා ගනිමින්, ගොනුවකට බහු-නූල් ලිවීමේ ගැටළු නොමැති බැවින්, ගොනු භාවිතා කිරීමට මම තීරණය කරමි.

Habr නූල් තුනකට වඩා භාවිතා කිරීම තහනම් කිරීමට පටන් ගනී.
හබ්ර් වෙත යාමට විශේෂයෙන් උද්යෝගිමත් උත්සාහයන් පැය කිහිපයක් සඳහා ip තහනමකින් අවසන් විය හැකිය. එබැවින් ඔබට භාවිතා කළ යුත්තේ නූල් 3 ක් පමණි, නමුත් මෙය දැනටමත් හොඳ ය, මන්ද ලිපි 100 කට වඩා පුනරාවර්තනය කිරීමේ කාලය තත්පර 26 සිට 12 දක්වා අඩු වේ.

මෙම අනුවාදය තරමක් අස්ථායී බව සඳහන් කිරීම වටී, බාගැනීම් වරින් වර ලිපි විශාල සංඛ්‍යාවක් මත වැටේ.

async_v1.py

from bs4 import BeautifulSoup
import requests
import os, sys
import json
from multiprocessing.dummy import Pool as ThreadPool
from datetime import datetime
import logging

def worker(i):
    currentFile = "files\{}.json".format(i)

    if os.path.isfile(currentFile):
        logging.info("{} - File exists".format(i))
        return 1

    url = "https://m.habr.com/post/{}".format(i)

    try: r = requests.get(url)
    except:
        with open("req_errors.txt") as file:
            file.write(i)
        return 2

    # Запись заблокированных запросов на сервер
    if (r.status_code == 503):
        with open("Error503.txt", "a") as write_file:
            write_file.write(str(i) + "n")
            logging.warning('{} / 503 Error'.format(i))

    # Если поста не существует или он был скрыт
    if (r.status_code != 200):
        logging.info("{} / {} Code".format(i, r.status_code))
        return r.status_code

    html_doc = r.text
    soup = BeautifulSoup(html_doc, 'html5lib')

    try:
        author = soup.find(class_="tm-user-info__username").get_text()

        timestamp = soup.find(class_='tm-user-meta__date')
        timestamp = timestamp['title']

        content = soup.find(id="post-content-body")
        content = str(content)
        title = soup.find(class_="tm-article-title__text").get_text()
        tags = soup.find(class_="tm-article__tags").get_text()
        tags = tags[5:]

        # Метка, что пост является переводом или туториалом.
        tm_tag = soup.find(class_="tm-tags tm-tags_post").get_text()

        rating = soup.find(class_="tm-votes-score").get_text()
    except:
        author = title = tags = timestamp = tm_tag = rating = "Error" 
        content = "При парсинге этой странице произошла ошибка."
        logging.warning("Error parsing - {}".format(i))
        with open("Errors.txt", "a") as write_file:
            write_file.write(str(i) + "n")

    # Записываем статью в json
    try:
        article = [i, timestamp, author, title, content, tm_tag, rating, tags]
        with open(currentFile, "w") as write_file:
            json.dump(article, write_file)
    except:
        print(i)
        raise

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("Необходимы параметры min и max. Использование: async_v1.py 1 100")
        sys.exit(1)
    min = int(sys.argv[1])
    max = int(sys.argv[2])

    # Если потоков >3
    # то хабр банит ipшник на время
    pool = ThreadPool(3)

    # Отсчет времени, запуск потоков
    start_time = datetime.now()
    results = pool.map(worker, range(min, max))

    # После закрытия всех потоков печатаем время
    pool.close()
    pool.join()
    print(datetime.now() - start_time)

තුන්වන අනුවාදය. අවසාන

දෙවන අනුවාදය දෝෂහරණය කරන අතරතුර, හබ්‍ර් හි හදිසියේම, වෙබ් අඩවියේ ජංගම අනුවාදයට ප්‍රවේශ වන API එකක් ඇති බව මම සොයා ගතිමි. එය විග්‍රහ කිරීමටවත් අවශ්‍ය නොවන json පමණක් බැවින් එය ජංගම අනුවාදයට වඩා වේගයෙන් පූරණය වේ. අවසානයේදී, මම මගේ පිටපත නැවත ලිවීමට තීරණය කළෙමි.

ඉතින්, හොයාගෙන මෙම සබැඳිය API, ඔබට එය විග්‍රහ කිරීම ආරම්භ කළ හැක.

async_v2.py

import requests
import os, sys
import json
from multiprocessing.dummy import Pool as ThreadPool
from datetime import datetime
import logging

def worker(i):
    currentFile = "files\{}.json".format(i)

    if os.path.isfile(currentFile):
        logging.info("{} - File exists".format(i))
        return 1

    url = "https://m.habr.com/kek/v1/articles/{}/?fl=ru%2Cen&hl=ru".format(i)

    try:
        r = requests.get(url)
        if r.status_code == 503:
            logging.critical("503 Error")
            return 503
    except:
        with open("req_errors.txt") as file:
            file.write(i)
        return 2

    data = json.loads(r.text)

    if data['success']:
        article = data['data']['article']

        id = article['id']
        is_tutorial = article['is_tutorial']
        time_published = article['time_published']
        comments_count = article['comments_count']
        lang = article['lang']
        tags_string = article['tags_string']
        title = article['title']
        content = article['text_html']
        reading_count = article['reading_count']
        author = article['author']['login']
        score = article['voting']['score']

        data = (id, is_tutorial, time_published, title, content, comments_count, lang, tags_string, reading_count, author, score)
        with open(currentFile, "w") as write_file:
            json.dump(data, write_file)

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("Необходимы параметры min и max. Использование: asyc.py 1 100")
        sys.exit(1)
    min = int(sys.argv[1])
    max = int(sys.argv[2])

    # Если потоков >3
    # то хабр банит ipшник на время
    pool = ThreadPool(3)

    # Отсчет времени, запуск потоков
    start_time = datetime.now()
    results = pool.map(worker, range(min, max))

    # После закрытия всех потоков печатаем время
    pool.close()
    pool.join()
    print(datetime.now() - start_time)

ලිපියට සහ එය ලියූ කතුවරයාට අදාළ ක්ෂේත්‍ර එහි අඩංගු වේ.

API.png

සියලුම Habr එක දත්ත ගබඩාවක

මම සෑම ලිපියකම සම්පූර්ණ json ඉවත නොදැමූ නමුත් මට අවශ්‍ය ක්ෂේත්‍ර පමණක් ඉතිරි කළෙමි:

  • id
  • නිබන්ධනයයි
  • කාලය_ප්‍රකාශනය
  • ශීර්ෂය
  • අන්තර්ගතය
  • අදහස්_ගණනය
  • lang යනු ලිපිය ලියා ඇති භාෂාවයි. මෙතෙක් එහි ඇත්තේ en සහ ru පමණි.
  • tags_string - පෝස්ට් එකෙන් සියලුම ටැග්
  • කියවීමේ_ගණනය
  • කර්තෘ
  • ලකුණු - ලිපි ශ්රේණිගත කිරීම.

මේ අනුව, API භාවිතා කරමින්, මම ස්ක්‍රිප්ට් ක්‍රියාත්මක කිරීමේ කාලය url 8කට තත්පර 100 දක්වා අඩු කළෙමි.

අපට අවශ්‍ය දත්ත බාගත කිරීමෙන් පසුව, අපි එය සකස් කර දත්ත සමුදායට ඇතුළත් කළ යුතුය. මටත් මේ ගැන කිසිම ගැටලුවක් තිබුණේ නැහැ:

parser.py

import json
import sqlite3
import logging
from datetime import datetime

def parser(min, max):
    conn = sqlite3.connect('habr.db')
    c = conn.cursor()
    c.execute('PRAGMA encoding = "UTF-8"')
    c.execute('PRAGMA synchronous = 0') # Отключаем подтверждение записи, так скорость увеличивается в разы.
    c.execute("CREATE TABLE IF NOT EXISTS articles(id INTEGER, time_published TEXT, author TEXT, title TEXT, content TEXT, 
    lang TEXT, comments_count INTEGER, reading_count INTEGER, score INTEGER, is_tutorial INTEGER, tags_string TEXT)")
    try:
        for i in range(min, max):
            try:
                filename = "files\{}.json".format(i)
                f = open(filename)
                data = json.load(f)

                (id, is_tutorial, time_published, title, content, comments_count, lang,
                 tags_string, reading_count, author, score) = data

                # Ради лучшей читаемости базы можно пренебречь читаемостью кода. Или нет?
                # Если вам так кажется, можно просто заменить кортеж аргументом data. Решать вам.

                c.execute('INSERT INTO articles VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (id, time_published, author,
                                                                                        title, content, lang,
                                                                                        comments_count, reading_count,
                                                                                        score, is_tutorial,
                                                                                        tags_string))
                f.close()

            except IOError:
                logging.info('FileNotExists')
                continue

    finally:
        conn.commit()

start_time = datetime.now()
parser(490000, 490918)
print(datetime.now() - start_time)

සංඛ්‍යාලේඛන

හොඳයි, සාම්ප්‍රදායිකව, අවසාන වශයෙන්, ඔබට දත්ත වලින් සමහර සංඛ්‍යාලේඛන උපුටා ගත හැකිය:

  • අපේක්ෂිත බාගත කිරීම් 490 න් බාගත කර ඇත්තේ ලිපි 406 ක් පමණි. හබ්රේ පිළිබඳ ලිපිවලින් අඩකට වඩා (228) සඟවා හෝ මකා දමා ඇති බව පෙනේ.
  • ලිපි මිලියන භාගයකට ආසන්න සංඛ්‍යාවකින් සමන්විත සම්පූර්ණ දත්ත සමුදාය 2.95 GB බරයි. සම්පීඩිත ආකාරයෙන් - 495 MB.
  • සමස්තයක් වශයෙන්, පුද්ගලයන් 37804 ක් Habré හි කතුවරුන් වේ. මෙම සංඛ්‍යාලේඛන සජීවී පෝස්ට් වලින් පමණක් බව මම ඔබට මතක් කරමි.
  • Habré හි වඩාත්ම ඵලදායී කතුවරයා - අලිසාර් - ලිපි 8774.
  • ඉහළම ශ්රේණිගත ලිපිය - 1448 ප්ලස්
  • වැඩිපුරම කියවන ලිපිය - 1660841 දසුන්
  • වැඩිපුරම සාකච්ඡා කළ ලිපිය - 2444 අදහස්

හොඳයි, මුදුන් ස්වරූපයෙන්ඉහළම කතුවරුන් 15සියලුම Habr එක දත්ත ගබඩාවක
ශ්‍රේණිගත කිරීම අනුව ඉහළම 15සියලුම Habr එක දත්ත ගබඩාවක
ඉහළම 15 කියවන්නසියලුම Habr එක දත්ත ගබඩාවක
ඉහළම 15 සාකච්ඡා කළාසියලුම Habr එක දත්ත ගබඩාවක

මූලාශ්රය: www.habr.com

අදහස් එක් කරන්න