파이썬 크롤링 에러입니다. 'NoneType' object is not subscriptable

조회수 6674회

장고 모델을 만들고 view 화면에 아래처럼 코드를 작성했습니다.

def scrape(request):
    from bs4 import BeautifulSoup
    import requests

    if request.method == "POST":
        keyword = request.POST.get("keyword")
        page = request.POST.get("page")

        for i in range(1, int(page) + 1):
            req = requests.get(
                "https://coinpan.com/?error_return_url=%2Ffree&vid=&mid=free&act=IS&is_keyword="
                + keyword
                + "&where=document&page="
                + str(i)
            )
            soup = BeautifulSoup(req.content, "html.parser")

            for i in soup.find_all("a", class_="document_link"):
                keyword = i.text

                link_address = "https://coinpan.com/" + i.find("a")["href"]

                if link_address != "" and keyword is not None:  
                    Keyword.objects.create(
                        word=keyword, link=link_address,
                    ) 
                    data = Keyword.objects.all()
            return render(request, "scrape_result.html", {"data": data})

    else:

        return render(request, "index.html", {})

실행하면,

위에 < link_address = "https://coinpan.com/" + i.find("a")["href"] > 이 부분이 아래처럼 에러 나옵니다.

" TypeError at /
'NoneType' object is not subscriptable" 

자료를 아무리 찾아봐도 문제를 모르겠어요.

  • 장고보단 beautifulsoup 문제라서 질문, 태그 수정했습니다. 편집요청빌런 2020.4.8 08:59

1 답변

  • object is not subscriptable 같은 오류는 다음과 같은 경우에 나옵니다.

    >>> 0[3]
    Traceback (most recent call last):
      File "<pyshell#27>", line 1, in <module>
        0[3]
    TypeError: 'int' object is not subscriptable
    >>> a = None
    >>> a[3]
    Traceback (most recent call last):
      File "<pyshell#29>", line 1, in <module>
        a[3]
    TypeError: 'NoneType' object is not subscriptable
    >>> a['ref']
    Traceback (most recent call last):
      File "<pyshell#30>", line 1, in <module>
        a['ref']
    TypeError: 'NoneType' object is not subscriptable
    
    

    위 예제에서는 aNone이고, 이 오브젝트에 대해 정수인덱스나 문자열키로 오브젝트 안의 요소를 접근하려는 시도에서 예외가 발생한 것입니다.

    보여주신 코드에서는 i.find("a")["href"] 부분에서 i.find("a")None을 반환했을 것입니다.

    • 알려주신대로 수정하니 해결 됐습니다. i.get("href")로 수정했어요. 감사합니다! yubin cho 2020.4.7 22:03

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)