簡體   English   中英

AttributeError: 'NoneType' object 沒有屬性 'attrs',我在嘗試從 url 抓取圖像時遇到此錯誤。 我該如何解決?

[英]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' object 沒有屬性 '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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM