1. 설명
- requests, BeautifulSoup 패키지를 이용하여 블로그(예 : blogspot) html 파싱
- 사이트맵(웹사이트 내 모든 페이지 목차) 내 블로그 글에서 제목만 추출하고 싶음.
2. 사전 필요
- 파싱할 웹페이지(예 : https://blog.hkand.com)
- 사이트맵 주소(예 : /sitemap.xml?page=1, /sitemap.xml?page=2)
3. 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 | import requests
from bs4 import BeautifulSoup
sitemap_urls = [
"https://blog.hkand.com/sitemap.xml?page=1",
"https://blog.hkand.com/sitemap.xml?page=2"
]
for sitemap_url in sitemap_urls:
response = requests.get(sitemap_url)
soup = BeautifulSoup(response.text,"html.parser")
urls = soup.find_all("loc")
for url in urls:
if url.text.startswith("https") and url.text.endswith(".html"):
post_response = requests.get(url.text)
post_soup = BeautifulSoup(post_response.text,"html.parser")
title = post_soup.find("h3", class_="post-title entry-title")
if title:
print(title.text.strip())
|
4. 기타
- [구글 코랩] https://blog.hkand.com/2023/01/blog-post.html
끝.