Key error ошибка в парсере

from urllib.request import *
from bs4 import BeautifulSoup

url ="https://oboitut.com/hi-tech/page/"

def get_html(url):
    req = Request(url)
    html = urlopen(req).read()
    return html

def main():
    opener = build_opener()
    opener.addheaders = [("User agent", "Mozzila/5.0")]
    install_opener(opener)
    for i in range(1,2):
        html = get_html(url + str(i))
        soup = BeautifulSoup(html, "html.parser")
        list = soup.find_all(class_="screen-link")
        for a in list:
            second_html = get_html(a["href"])
            second_html_soup = BeautifulSoup(second_html, "html.parser")
            image = second_html_soup.find(class_="screen").get("src")
            urlretrieve(image, image[41:])
            print(image[41:], "Скачан")


main()

Выдаёт ошибку:

Traceback (most recent call last):
  File "Dogparse.py", line 27, in <module>
main()
  File "Dogparse.py", line 20, in main
second_html = get_html(a["href"])
  File "/home/bestway/.local/lib/python3.6/site-packages/bs4/element.py", line 1401, in __getitem__
return self.attrs[key]
KeyError: 'href

Как можно исправить ошибку Схожий код работал без ошибок

from urllib.request import *
from bs4 import BeautifulSoup

url ="https://wallhaven.cc/random?seed=uC0QY&page=5"

def get_htlm(url):
    req = Request(url)
    html = urlopen(req).read()
    return html

def main():
    opener = build_opener()
    opener.addheaders = [("User agent", "Mozzila/5.0")]
    install_opener(opener)
    for i in range(1,9):
        html = get_htlm(url + str(i))
        soup = BeautifulSoup(html, 'html.parser')
        list = soup.find_all(class_="preview")
        for a in list:
            second_html = get_htlm(a["href"])
            second_html_soup = BeautifulSoup(second_html, "html.parser")
            image = second_html_soup.find(id="wallpaper").get("data-cfsrc")
            urlretrieve(image, image[41:])
            print(image[41:],"Скачан")


main()

Помогите понять в чем ошибка.


Ответы (0 шт):