공백삭제 관련질문드립니다
조회수 122회
학교 공지를 가져오는 코드를 가져와서 출력했을때 \t
\n
\r
들이뜨며 csv파일로 변환했을때
0,"
[공지] 인문과학 융합 프로젝트 설명회 안내
"
1,"
제44회 공군참모총장배 Space Challenge 2023 경인지역 예선대회
"
2,"
같이 공백이 많아 replace를 이용하여 공백을 제거하여도 공백이 사라지지않습니다 답변 부탁드립니다
//import requests
from bs4 import BeautifulSoup
import pandas as pd
url = 'https://seowon-h.goeyi.kr/seowon-h/na/ntt/selectNttList.do?mi=16474&bbsId=9508'
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
now = soup.find_all(class_='nttInfoBtn')
ha = []
for i in now:
ha.append(i.text)
#위에까진 ha가 list
str1 = ""
str1 = "".join(ha)
str1 = str1.replace(' ', '') #공백 삭제 부분
#여기까진 ha가 str1에 흡수됨
fin =list(str1)
print(fin)
df = pd.DataFrame(fin)
df.to_csv('학교공지.csv')
1 답변
-
앞 뒤의 공백을 없애려면 replace() 대신 strip()을 쓰면 됩니다.
그리고 공백을 없애는 시점이 잘못됐습니다. 이렇게 해보세요:
from bs4 import BeautifulSoup import requests url = 'https://seowon-h.goeyi.kr/seowon-h/na/ntt/selectNttList.do?mi=16474&bbsId=9508' response = requests.get(url) html = response.text soup = BeautifulSoup(html, 'html.parser') now = soup.find_all(class_='nttInfoBtn') ha = [] for i in now: ha.append(i.text.strip() + '\n') str1 = "" str1 = "".join(ha) print(str1)
댓글 입력