파이썬 크롤링 에러입니다. '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"
자료를 아무리 찾아봐도 문제를 모르겠어요.
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
위 예제에서는
a
가None
이고, 이 오브젝트에 대해 정수인덱스나 문자열키로 오브젝트 안의 요소를 접근하려는 시도에서 예외가 발생한 것입니다.보여주신 코드에서는
i.find("a")["href"]
부분에서i.find("a")
가None
을 반환했을 것입니다.
댓글 입력