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

Так что мой код работает, но только для одного URL.(например, я использовал http://www.ancient -hebrew.org / m / dictionary / 1000.html )

Однако я хотел бы применить каждый URL-адрес html-файла к своему коду.Который можно найти здесь (https://www.ancient -hebrew.org / m / dictionary / ).

from bs4 import BeautifulSoup
import re
import urllib


def getImage(_list):
    images = []
    # adds the url
    for image in _list:
        images.append(re.sub(
            r"..\/..\/", r"http://www.ancient-hebrew.org/", image['src']))
    return images


def getAudioFile(_list):
    audio = []
    # removes a tab character + adds the url
    for l in _list:
        audio.append("http://www.ancient-hebrew.org/m/dictionary/" +
                     l['href'].replace("\t", ''))
    return ''.join(audio)


def getHebrewWord(_list):
    hebrew = []
    for f in _list:
        hebrew.append(f.string.strip())
    return ''.join(hebrew)


url = 'http://www.ancient-hebrew.org/m/dictionary/1000.html'
file_name = str(re.search(r'(\d+).\w+$', url).group(1)) + ".txt"
raw_html = urllib.urlopen(url).readlines()
_list = []
_dict = {}
_ignore = {'audioURLs': '', 'pronuncation': [],
           'imageURLs': [], 'hebrewWord': ''}
for line in raw_html:
    number = 1
    html = BeautifulSoup(line, 'lxml')

    # Image Files URLs
    images = getImage(html.find_all('img', src=re.compile('.jpg$')))

    # Audio File URLs
    audioFile = getAudioFile(html.find_all('a', href=re.compile('.mp3$')))

    # Hebrew Words
    hebrewWords = getHebrewWord(html.find_all('font', face="arial", size="+1"))

    # Pronunciations
    pronunciation = [item.next_sibling.strip()
                     for item in html.select('img + font')]

    # Output: {'audioURLs': '', 'pronuncation': [], 'imageURLs': [], 'hebrewWord': ''}
    dictionary = {
        'audioURLs': audioFile,
        'pronuncation': pronunciation,
        'imageURLs': images,
        'hebrewWord': hebrewWords
    }
    if dictionary != _ignore:
        _list.append(dictionary)

with open(file_name, 'w') as f:
    for item in _list:
        f.write("%s\n" % item)

Итак, в конце я хотел бы записать их в столько файлов.Что было бы простым способом сделать это.

1 Ответ

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

Мне кажется, вы сделали это несколько сложнее (и - кардинальный грех! - использовали регулярные выражения в html D :).Я попытался упростить некоторые его части - получить ссылки на изображения и звуки и вставить их в списки.Обратите внимание, что по разным причинам я изменил некоторые из названий переменных, которые вы использовали, но должно быть относительно легко вписать все в вашу структуру и расширить ее, чтобы получить само слово:

from bs4 import BeautifulSoup as bs
import requests

url = 'http://www.ancient-hebrew.org/m/dictionary/1000.html'
raw_html = requests.get(url)

soup = bs(raw_html.content, 'lxml')

image_list = []
audio_list = []

images = soup.find_all ('img')
audios = soup.find_all ('a',href=True)

for image in images:
    if 'jpg' in image['src']:
        image_link = "http://www.ancient-hebrew.org/"+image['src'].replace('../../','')
        image_list.append(image_link)

for audio in audios:
    if 'mp3' in audio['href']:
        audio_link = "http://www.ancient-hebrew.org/m/dictionary/"+audio['href'].replace("\t", '')
        audio_list.append(link)

и т. Д.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...