하얀설표 블로그




해결)ResultSet object has no attribute *. You're probably treating a list of elements like a single element.





( 수정됨)


에러 예시

# text, get_text, getText
from bs4 import BeautifulSoup
html = '<p>하얀설표 블로그</p>'
soup = BeautifulSoup(html, 'html.parser')
a = soup.select('p')
a: BeautifulSoup
a.get_text()

>> Traceback (most recent call last):
  File "c:\seolpyo\example.py", line 6, in <module>
    a.get_text()
    ^^^^^^^^^^
  File "C:\seolpyo\Lib\site-packages\bs4\element.py", line 2428, in __getattr__
    raise AttributeError(
AttributeError: ResultSet object has no attribute 'get_text'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

# select, select_one
from bs4 import BeautifulSoup
html = '<p>하얀설표 블로그</p>'
soup = BeautifulSoup(html, 'html.parser')
a = soup.select('p')
a: BeautifulSoup
a.select('p')

>> Traceback (most recent call last):
  File "c:\seolpyo\example.py", line 6, in <module>
    a.select('p')
    ^^^^^^^^
  File "C:\seolpyo\Lib\site-packages\bs4\element.py", line 2428, in __getattr__
    raise AttributeError(
AttributeError: ResultSet object has no attribute 'select'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

# find_all
from bs4 import BeautifulSoup
html = '<p>하얀설표 블로그</p>'
soup = BeautifulSoup(html, 'html.parser')
a = soup.select('p')
a: BeautifulSoup
a.find_all('p')

>> Traceback (most recent call last):
  File "c:\seolpyo\example.py", line 6, in <module>
    a.find_all('p')
    ^^^^^^^^^^
  File "C:\seolpyo\Lib\site-packages\bs4\element.py", line 2428, in __getattr__
    raise AttributeError(
AttributeError: ResultSet object has no attribute 'find_all'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

해결방법

bs4.element.Tag 객체에 사용하는 명령을 list 객체에 사용하지 말자.

설명

문제의 원인은 명확하다. find_all 또는 select 명령을 통해 가져온 결과에 bs4.BeautifulSoup 또는 bs4.element.Tag 객체에 사용 가능한 명령을 사용한 것이다.

find_all과 select docstring(설명)을 읽어보면 모두 ResultSet[Tag] 을 return한다고 되어 있는데, bs4.element.Tag 객체가 들어있는 list 객체를 반환한다는 뜻이다.
만약 결과가 없다면 빈 리스트를 return한다.
이 명령을 사용했다면 bs4.element.Tag는 리스트 안에 있기 때문에 index를 호출해 꺼내오거나, 루프문에서 호출되는 요소를 사용해야한다.

만약 1개의 태그만을 찾는 것이 목적이라면 find나 select_one 명령을 통해 1개의 bs4.element.Tag 객체를 가져올 수도 있다.

루프를 돌려보거나, find 또는 select_one 명령을 통해 list가 아닌 bs4.element.Tag을 가져와 그 다음 명령을 실행해보면 코드가 문제없이 작동하는 것을 확인할 수 있다.

html = '<p>하얀설표 블로그</p>'
soup = BeautifulSoup(html, 'html.parser')
a = soup.select_one('p')
print(a.text)
a = soup.find('p')
print(a.text)
for i in soup.select('p'):
    print(i.text)

>> 하얀설표 블로그
하얀설표 블로그
하얀설표 블로그


공감 : 0







white.seolpyo.com