AttributeError: 'NoneType' object has no attribute 'attrs', I am getting this error while I am trying to scrape images from the url. How can I fix it?

AttributeError: 'NoneType' object has no attribute 'attrs', I am getting this error while I am trying to scrape images from the url. How can I fix it?

import bs4
import requests
url ="https://www.passiton.com/inspirational-quotes?page=2"
response = requests.get(url)
soup = bs4.BeautifulSoup(response.content)
article_element = soup.findAll('img')

for i, article in enumerate(article_element):
with open('inspiration{}.jpg'.format(i),'wb') as file:
    img_url = article.img.attrs['src']
    response = requests.get(img_url)

    file.write(response.content)

AttributeError:'NoneType' 对象没有属性 'attrs',我在尝试从 url 抓取图像时遇到此错误。我该如何解决?请帮我解决这个错误

我不确定你想用 article.img.attrs['src'] 实现什么。在您的示例中,您可以只使用 article[src] 来获取相对图像 URL 。将其与主要 URL 相结合,您应该能够获取图像。这应该可以解决您的错误:


import bs4
import requests
main_url = "https://www.passiton.com/"
url ="https://www.passiton.com/inspirational-quotes?page=2"
response = requests.get(url)
soup = bs4.BeautifulSoup(response.content)
article_element = soup.findAll('img')

for i, article in enumerate(article_element):
with open('inspiration.jpg','wb') as file:
    img_url = main_url+article['src']
    response = requests.get(img_url)
    file.write(response.content)

为避免字典中没有键时崩溃,请使用

dict.get('key')  # returns value or None

而不是

dict['key']  # returns value or crash