Попробуйте и за исключением того, что не работает с IndexError - PullRequest
0 голосов
/ 19 мая 2019

Я пытаюсь проанализировать изображения из двух мест на 82 URL-адресах с помощью Beautifulsoup.Расположение: img_page и img_gallery.В любом из этих двух мест должно быть изображение, которое я хочу проанализировать.Код работал до тех пор, пока ни в одном месте не было изображения, и я получил бы следующую ошибку:

***GALLERY*** /images/africa/egypt/abu-gorab-sun-temples/gallery/sun-temple-of-niuserre-2.jpg
***GALLERY*** /images/africa/egypt/abu-roash-pyramid-of-djedefre/gallery/abu-roash-pyramid-of-djedefre-10.jpg
***GALLERY*** /images/africa/egypt/abusir-necropolis/gallery/abusir-necropolis-01.jpg
***GALLERY*** /images/africa/egypt/dashur-bent-pyramid/gallery/dashur-bent-pyramid-01.jpg
***GALLERY*** /images/africa/egypt/giza-plateau-pyramid-complex/gallery/giza-plateau-pyramid-complex-01.jpg
***GALLERY*** /images/africa/egypt/giza-plateau-sphinx/gallery/giza-plateau-sphinx-01.jpg
***GALLERY*** /images/africa/egypt/giza-plateau-valley-temple/gallery/giza-plateau-valley-temple-01.jpg
***GALLERY*** /images/africa/egypt/saqqara-serapeum/gallery/saqqara-serapeum-01.jpg
***GALLERY*** /images/africa/egypt/zawyet-el-aryan-unfinished-pyramid/gallery/zawyet-el-aryan-unfinished-pyramid-01.jpg
***GALLERY*** /images/africa/egypt/abu-simbel-temple-complex/gallery/abu-simbel-temple-complex-01.jpg
***GALLERY*** /images/africa/egypt/abydos-osireion/gallery/osireion-abydos-01.jpg
**PAGE*** /images/africa/egypt/aswan-elephantine-island/aswan-elephantine-island-main.jpg
***GALLERY*** /images/africa/egypt/aswan-unfinished-obelisk/gallery/aswan-unfinished-obelisk-01.jpg
***GALLERY*** /images/africa/egypt/denderra-temple-complex/gallery/denderra-temple-complex-01.jpg
***GALLERY*** /images/africa/egypt/thebes-karnak-temple-complex/gallery/thebes-karnak-temple-complex-01.jpg
***GALLERY*** /images/africa/egypt/thebes-luxor-temple/gallery/thebes-luxor-temple-01.jpg
***GALLERY*** /images/africa/ethiopia/axum-obelisks/gallery/axum-obelisks-01.jpg
**PAGE*** /images/africa/ethiopia/lalibela-rock-hewn-churches/lalibela-rock-hewn-churches-main3.jpg
***GALLERY*** /images/asia/india/ellora-kailasa-temple/gallery/ellora-kailasa-temple-01.jpg
***GALLERY*** /images/asia/india/warangal-warangal-fort/gallery/warangal-warangal-fort-01.jpg
***GALLERY*** /images/asia/indonesia/west-java-gunung-padang/gallery/west-java-gunung-padang-01.jpg
***GALLERY*** /images/asia/israel/jerusalem-western-wall/gallery/jerusalem-western-wall01.jpg
***GALLERY*** /images/asia/japan/asuka-ishibutai-kofun/gallery/asuka-ishibutai-kofun-01.jpg
***GALLERY*** /images/asia/japan/asuka-masuda-no-iwafune/gallery/asuka-masuda-no-iwafune-01.jpg
**PAGE*** /images/asia/japan/yonaguni-yonaguni-monument/yonaguni-yonaguni-monument-main1.jpg
***GALLERY*** /images/asia/laos/xiangkhouang-plain-of-jars/gallery/xiangkhouang-plain-of-jars-01.jpg
***GALLERY*** /images/asia/lebanon/baalbek-baalbek-temple-complex/gallery/baalbek-baalbek-temple-complex-01.jpg
**PAGE*** /images/asia/micronesia/pohnpei-nan-madol/pohnpei-nan-madol-main1.jpg
***GALLERY*** /images/asia/south-korea/ganghwa-ganghwa-dolmen-site/gallery/ganghwa-ganghwa-dolmen-site-01.jpg
Traceback (most recent call last):
  File "c:/Users/JGrov/Google Drive/pythonProjects/Megalith Map/image.py", line 42, in <module>
    img_src = img_page[0].get('src', '')
IndexError: list index out of range

Затем я подумал, что могу использовать try и except, чтобы сохранить скрипт и добавить 'No Images Found' кsite_img но я не могу заставить его работать.Какие-либо предложения?Спасибо!

Мой текущий код:

site_link = []
site_img = []
for i in site_links:
    r = requests.get(i).text
    soup = bs4.BeautifulSoup(r, 'html5lib')
    img_page = soup.find('div', {'itemprop' : 'blogPost'}).find_all('img')
    img_src = img_page[0].get('src', '')
    img_gallery = soup.find('a', {'class':'sigProLink fancybox-gallery', 'href':True})
    if img_gallery:
        href = img_gallery.get('href', '')
        if '.jpg' in href:
            img_link = '***GALLERY*** ' + href
            site_img.append(img_link)
            print(img_link)
    else:                               
        try:
            if '.jpg' in img_src:
                    img_link = '**PAGE*** ' + img_src       
                    site_img.append(img_link)
                    print(img_link)
        except IndexError:
                nf = 'No Images Found'
                site_img.append(nf)
                print('nf')

1 Ответ

1 голос
/ 19 мая 2019

Попробуйте поместить оператор обработки ошибок в строку:

img_src = img_page[0].get('src', '')

В соответствии с ошибкой вы получаете пустой массив img_page .

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