
현재 보여지는 Medium
if response.status_code == 200:
html = response.text
soup = BeautifulSoup(html, 'html.parser')
# CSS 선택자 수정
# title = soup.select('title')
title = soup.select('#root > div > div.n.cx > div.jq.ah > div > div > div > div.al.ah > div > div:nth-child(1) > div > div > div.n.cx > div:nth-child(2) > a > div > h2')
if title:
print(title[0].text)
else:
print("title not found")
else:
print("Failed to retrieve the page. Status code: ",response.status_code)

일단 이렇게 제목 하나는 불러왔다.
그런데 이걸 for문으로 6개를 불러오는게 오전까지 잘 안됐었다.😢
그런데!
방금 다시 시도했더니 해결해서 해결한 과정을 기록해보겠다!
아까 위에서 제목 한줄을 뽑았으니 이걸 for문으로 한번에 여러 제목을 불러와보자.

첫번째 주제가 있는 div 박스 부분 Copy selector로 주소 복사
<첫번째 주제 주소>
#root > div > div.n.cx > div.kc.ah > div > div > div > div.al.ah > div > div:nth-child(1) > div > div > div.n.cx > div:nth-child(2) > a > div > h2

두번째 주제 div 박스 부분 Copy selector로 주소 복사
<두번째 주제 주소>
#root > div > div.n.cx > div.kc.ah > div > div > div > div.al.ah > div > div:nth-child(2) > div > div > div.n.cx > div:nth-child(2) > a > div > h2
div:nth-child(1) -> div:nth-child(2)
해당 부분에서 숫자만 바뀌는걸 확인
최대한 위에서 제목을 도출했던 코드를 살리면서 for문을 작성했다.
if response.status_code == 200:
html = response.text
soup = BeautifulSoup(html, 'html.parser')
data = []
# CSS 선택자 수정
# title = soup.select('title')
for topic_num in range(1,7):
title = soup.select(f'#root > div > div.n.cx > div.jq.ah > div > div > div > div.al.ah > div > div:nth-child({topic_num}) > div > div > div.n.cx > div:nth-child(2) > a > div > h2')
# data.append(data)
if title:
# print(title[0].text)
titles = title[0].text
data.append({
'Title': titles
})
else:
print("title not found")
else:
print("Failed to retrieve the page. Status code: ",response.status_code)
topics = pd.DataFrame(data)
topics


오전 점심 내내 날 헤매게 한 gpt가 준 코드는 갖다버려야겠다.
gpt는 정답이 아니라는걸 여기서 또 한번 느꼈다.
다음에는 작성일자까지 추가로 불러와볼 예정이다.