Как построить словарь для каждой строки в файле HTML - PullRequest
0 голосов
/ 11 июня 2019

Итак, я работаю с этим URL (http://www.ancient -hebrew.org / m / dictionary / 1000.html ).

И я пытаюсь создать словарь для каждогоВвод слова на иврите.

То, что у меня есть сейчас, просто выводит каждый файл, который я пытаюсь собрать.Тем не менее, я застрял в том, как пройтись по каждому слову на сайте и создать словарь для него.Ниже приведен мой код.

from bs4 import BeautifulSoup
import re

raw_html = open('/Users/gansaikhanshur/TESTING/webScraping/1000.html').read()
# lxml is faster. If you don't have it, pip install lxml
html = BeautifulSoup(raw_html, 'lxml')

# outputs: "http://www.ancient-hebrew.org/files/heb-anc-sm-beyt.jpg"
images = html.find_all('img', src=re.compile('.jpg$'))
for image in images:
    image = re.sub(
        r"..\/..\/", r"http://www.ancient-hebrew.org/", image['src'])
    # print(image)

# outputs: "unicode_hebrew_text"
fonts = html.find_all('font', face="arial", size="+1")
for f in fonts:
    f = f.string.strip()
    print(f)

# outputs: "http://www.ancient-hebrew.org/m/dictionary/audio/998.mp3"
mp3links = html.find_all('a', href=re.compile('.mp3$'))
for mp3 in mp3links:
    mp3 = "http://www.ancient-hebrew.org/m/dictionary/" + \
        mp3['href'].replace("\t", '')
    # print(mp3)

Итак, в файле HTML у нас есть, например,

<!--501-1000--> <A Name=    505 ></A>   <IMG SRC="../../files/heb-anc-sm-pey.jpg"><IMG SRC="../../files/heb-anc-sm-lamed.jpg"><IMG SRC="../../files/heb-anc-sm-aleph.jpg">   <Font face="arial" size="+1">  &#1488;&#1462;&#1500;&#1462;&#1507; </Font>     e-leph  <BR>    Thousand    <BR>    Ten times one hundred in amount or number.  <BR>Strong's Number:    505 <BR><A HREF="audio/ 505 .mp3"><IMG SRC="../../files/icon_audio.gif"  width="25" height="25" border="0"></A><BR> <A HREF=../ahlb/aleph.html#505><Font color=A50000><B>AHLB</B></Font></A>    <HR>
    <A Name=    517 ></A>   <IMG SRC="../../files/heb-anc-sm-mem.jpg"><IMG SRC="../../files/heb-anc-sm-aleph.jpg">   <Font face="arial" size="+1">  &#1488;&#1461;&#1501;   </Font>     eym <BR>    Mother  <BR>    A female parent. Maternal tenderness or affection. One who fulfills the role of a mother.   <BR>Strong's Number:    517 <BR><A HREF="audio/ 517 .mp3"><IMG SRC="../../files/icon_audio.gif"  width="25" height="25" border="0"></A><BR> <A HREF=../ahlb/aleph.html#517><Font color=A50000><B>AHLB</B></Font></A>    <HR>
    <A Name=    518 ></A>   <IMG SRC="../../files/heb-anc-sm-mem.jpg"><IMG SRC="../../files/heb-anc-sm-yud.jpg"><IMG SRC="../../files/heb-anc-sm-aleph.jpg">     <Font face="arial" size="+1">  &#1488;&#1460;&#1501;   </Font>     eem <BR>    If  <BR>    Allowing that; on condition that. A desire to bind two ideas together.  <BR>Strong's Number:    518 <BR><A HREF="audio/ 518 .mp3"><IMG SRC="../../files/icon_audio.gif"  width="25" height="25" border="0"></A><BR> <A HREF=../ahlb/aleph.html#518><Font color=A50000><B>AHLB</B></Font></A>    <HR>

. Я бы хотел просмотреть каждый из них, но они начинаются со строки 100. Яхотел бы, чтобы он работал для каждого файла, который похож на этот, поэтому я не могу указать номер строки.Я скачал html с помощью wget.

Или было бы проще использовать xpath?

Итак, в конце я хотел бы получить что-то вроде ниже.

{dict_1: [img1, img2, img3], hebrewTxt: hebrewtxt, pronunciation: prununciation, audio_file: audiofile}
{dict_2: [img1, img2, img3, img4], hebrewTxt: hebrewtxt, pronunciation: prununciation, audio_file: audiofile}
{dict3... and so on

1 Ответ

0 голосов
/ 11 июня 2019

Мне кажется, что (почти) каждая строка представляет собой набор img, mp3, шрифт и т. Д.
следовательно, я думаю, что вы можете анализировать html построчно и извлекать необходимую информацию на лету.

Ради простоты я создал только функции для извлечения ссылки на исходное изображение src и медиа ссылки mp3.

from bs4 import BeautifulSoup
import re

def getsrc(str):
    """ Get a string and returns the link of the src image, if any. None otherwise"""
    if str is not None:
        src = re.search('src="(.*\.jpg)"', str)
        if src is not None:
            return src.group(1)

    return None


def getmp3(str):
    """ Get a string and returns the link of the mp3 media, if any. None otherwise"""
    if str is not None:
        src = re.search('href="(.*\.mp3)"', str)
        if src is not None:
            return src.group(1)

    return None


# ---------------

raw_html = open('./page.html').readlines()

for line in raw_html:
    html = BeautifulSoup(line, 'lxml')

    # Image
    img = str(html.find('img'))
    src = getsrc(img)

    # Mp3 link
    a = str(html.find_all('a'))
    mp3 = getmp3(a)

    dictionary = {
        'src':src,
        'media': mp3
    }

    print(dictionary)

Вывод этого фрагмента выглядит примерно так:

{'src': './page_files/heb-anc-sm-hey.jpg', 'media': 'http://www.ancient-hebrew.org/m/dictionary/audio/998.mp3'}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...