반응형

 

 

bs4 예제를 따라해보면서 마주친 오류들 기록

 

 

 

TypeError: can only concatenate str (not "Tag") to str

 

TypeError: can only concatenate str (not "list") to str

 

TypeError: can only concatenate str (not "ResultSet") to str

 

 

사용 코드

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>

<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

soup = BeautifulSoup(html_doc)


print("p : " + soup.p)

 

 

스택오버플로우 답변들을 참고해보니 파이썬에서 print 메서드string 타입만 +를 사용한 출력이 가능하고

그 외의 사용법은 모두 콤마를 사용하여 출력해야 오류가 없는것같다

 

그래서 위의 타입에러가 발생한 이유는 태그나 리스트, ResultSet 타입을 형변환없이

바로 출력했기 때문

 

 

따라서 위의 마지막 print 문을 다음과 같이 수정하면 오류가 발생하지 않는다

 

print("p : " + str(soup.p))

//Or

print("p : ",soup.p)

 

 

+번외

print("p : " + str(soup.p))
# p : <p class="title"><b>The Dormouse's story</b></p>

print("p : ",soup.a , "q")
# p :  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a> q

print("p : "+str(soup.a) + "q")
# p : <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>q

print("p : ",soup.a, "q")
# p :  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a> q

print("p : ",soup.a, " q")
# p :  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>  q

print("p : "+str(soup.a) + " q")
# p : <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a> q

print에 띄어쓰기가 어떻게 출력되는지 궁금해서 테스트해봄

 

 

 

 

참고 : https://stackoverflow.com/questions/60491093/python-scraping-problem-typeerror-can-only-concatenate-str-not-resultset-t

 

Python scraping problem "TypeError: can only concatenate str (not "ResultSet") to str"

I am fresh noobster who tries to learn python as well as use it for webscraping. So I watched a few videos to learn the basics on youtube, followed the tutorial, however I cannot figure it out why my

stackoverflow.com

 

반응형

+ Recent posts