본문으로 바로가기

유튜브 네이버쇼핑 크롤링 예제를 따라하던 중 아래와 같은 에러가 발생함.

200 https://search.shopping.naver.com/search/all.nhn?query=숨셔바요&cat_id=&frm=NVSHATC
Traceback (most recent call last):
  File "c:\Users\davincii\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\ptvsd_launcher.py", line 43, in <module>
    main(ptvsdArgs)
  File "c:\Users\davincii\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 432, in main
    run()
  File "c:\Users\davincii\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 316, in run_file
    runpy.run_path(target, run_name='__main__')
  File "C:\ProgramData\Anaconda3\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\ProgramData\Anaconda3\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\ProgramData\Anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "e:\00_Jobs\Crawling_Naver\stage_naver_shopping.py", line 11, in <module>
    products = parse(pageString)
  File "e:\00_Jobs\Crawling_Naver\parser_custom.py", line 33, in parse
    product = getProductInfo(li)
  File "e:\00_Jobs\Crawling_Naver\parser_custom.py", line 22, in getProductInfo
    return {"name":alt, "price":priceReload.text.replace(",", ""), "link":href}
AttributeError: 'NoneType' object has no attribute 'text'

'AttributeError 크롤링 예외처리'를 구글링하여 확인한 결과, BeautifulSoup에서 정의된 속성을 찾을 수 없어 None을 return하였고, None에 text attribute를 사용하려고 하니 에러가 발생한 것으로 추정

1. 어느 li에서 에러가 발생한 것인지 확인하기 위해, AttributeError가 발생하면 빈 string을 return하도록 예외처리 추가함.

def getProductInfo(li):
    # print(li)
    try:
        img = li.find("img")
        alt = img['alt']
        priceReload = li.find("span", {"class":"_price_reload"})
        aTit = li.find("a", {"class":"link"})
        href = aTit['href']

        return {"name":alt, "price":priceReload.text.replace(",", ""), "link":href}
    except AttributeError as e:
        return {"name":'', "price":'', "link":''}

 

2. 엑셀로 저장한 데이터를 보니 19번과 21번에 문제가 있음을 확인함

 

 

3. '핫딜'이라고 표시된 19번과 21번의 class가 _price_reload가 아닌 num으로 되어 있어서 발생한 에러임을 확인함

 

 

 

4. 예외처리 구문을 수정하여 예외가 발생할 경우 num을 return하도록 수정하여 19, 21번도 받아올 수 있도록 함

def getProductInfo(li):
    # print(li)
    try:
        img = li.find("img")
        alt = img['alt']
        priceReload = li.find("span", {"class":"_price_reload"})
        aTit = li.find("a", {"class":"link"})
        href = aTit['href']

        return {"name":alt, "price":priceReload.text.replace(",", ""), "link":href}
    except AttributeError as e:
        img = li.find("img")
        alt = img['alt']
        priceReload = li.find("span", {"class":"num"})
        aTit = li.find("a", {"class":"link"})
        href = aTit['href']

        return {"name":alt, "price":priceReload.text.replace(",", ""), "link":href}
        # return {"name":'', "price":'', "link":''}

 

 

 

5. 결론적으로 예외처리를 사용하지 않고 그냥 가격은 num을 가져오도록 하면 됨....

def getProductInfo(li):
    # print(li)
    img = li.find("img")
    alt = img['alt']
    priceReload = li.find("span", {"class":"num"})
    aTit = li.find("a", {"class":"link"})
    href = aTit['href']

    return {"name":alt, "price":priceReload.text.replace(",", ""), "link":href}

<참고>

1. 예외처리 -기본 흐름

 

[Python] 예외처리 - try, except, else, finally

예외처리 - 기본 흐름 프로그래밍을 하다보면 필연적으로 수많은 오류들에 직면하게 됩니다. 오류가 발생하는 것이 보다 완성도 높은 프로그램을 만드는데 필요하긴 합니다만 상황에 따라 오류를 무시해야 할 경..

gomguard.tistory.com

2. AttributeError: 'NoneType' object has no attribute 'get_text' (공공 데이터 - 미세먼지 - 크롤링) 에러 질문 드립니다.

 

AttributeError: 'NoneType' object has no attribute 'get_text' (공공 데이터 - 미세먼지 - 크롤링) 에러 질문 드립니다. - 인프런

질문 - AttributeError: 'NoneType' object has no attribute 'get_text' (공공 데이터 - 미세먼지 - 크롤링) 에러 질문 드립니다. # 선생님 코드와 'stationname' -> 'cityName', 'pm10grade' -> 'pm10Value' 만 다를 뿐 (인증키 등 기본 정보도 다릅니다만) 유사한 코드를 작성했지만 get_text 에러가 발생했습니다. 처음에 print(res.text)를 해보니 해

www.inflearn.com

3. [파이썬으로 웹 크롤러 만들기] 첫 번째 웹 스크레이퍼(2/2)