update crawler for short url
This commit is contained in:
1 parent
2b777f5314
commit
94aae50564
2 files changed
+163
-4
No files matched your search
@@ -1,8 +1,10 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
import aiohttp
|
||||
import bs4
|
||||
|
||||
from config import crawler_settings
|
||||
|
||||
@@ -27,7 +29,7 @@ class NvMapScraper:
|
||||
"""
|
||||
|
||||
GRAPHQL_URL: str = "https://pcmap-api.place.naver.com/graphql"
|
||||
REQUEST_TIMEOUT = 30 # 초
|
||||
REQUEST_TIMEOUT = 120 # 초
|
||||
|
||||
OVERVIEW_QUERY: str = """
|
||||
query getAccommodation($id: String!, $deviceType: String) {
|
||||
@@ -65,6 +67,7 @@ query getAccommodation($id: String!, $deviceType: String) {
|
||||
self.rawdata: dict | None = None
|
||||
self.image_link_list: list[str] | None = None
|
||||
self.base_info: dict | None = None
|
||||
self.facility_info: str | None = None
|
||||
|
||||
def _get_request_headers(self) -> dict:
|
||||
headers = self.DEFAULT_HEADERS.copy()
|
||||
@@ -72,8 +75,19 @@ query getAccommodation($id: String!, $deviceType: String) {
|
||||
headers["Cookie"] = self.cookies
|
||||
return headers
|
||||
|
||||
def parse_url(self) -> str:
|
||||
async def parse_url(self) -> str:
|
||||
"""URL에서 place ID를 추출합니다. 단축 URL인 경우 실제 URL로 변환합니다."""
|
||||
place_pattern = r"/place/(\d+)"
|
||||
|
||||
# URL에 place가 없는 경우 단축 URL 처리
|
||||
if "place" not in self.url:
|
||||
if "naver.me" in self.url:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(self.url) as response:
|
||||
self.url = str(response.url)
|
||||
else:
|
||||
raise GraphQLException("This URL does not contain a place ID")
|
||||
|
||||
match = re.search(place_pattern, self.url)
|
||||
if not match:
|
||||
raise GraphQLException("Failed to parse place ID from URL")
|
||||
@@ -81,14 +95,17 @@ query getAccommodation($id: String!, $deviceType: String) {
|
||||
|
||||
async def scrap(self):
|
||||
try:
|
||||
place_id = self.parse_url()
|
||||
place_id = await self.parse_url()
|
||||
data = await self._call_get_accommodation(place_id)
|
||||
self.rawdata = data
|
||||
fac_data = await self._get_facility_string(place_id)
|
||||
self.rawdata["facilities"] = fac_data
|
||||
self.image_link_list = [
|
||||
nv_image["origin"]
|
||||
for nv_image in data["data"]["business"]["images"]["images"]
|
||||
]
|
||||
self.base_info = data["data"]["business"]["base"]
|
||||
self.facility_info = fac_data
|
||||
self.scrap_type = "GraphQL"
|
||||
|
||||
except GraphQLException:
|
||||
@@ -141,7 +158,7 @@ query getAccommodation($id: String!, $deviceType: String) {
|
||||
f"Request failed with status {response.status}"
|
||||
)
|
||||
|
||||
except TimeoutError:
|
||||
except (TimeoutError, asyncio.TimeoutError):
|
||||
logger.error(f"[NvMapScraper] Timeout - place_id: {place_id}")
|
||||
print(f"[NvMapScraper] Timeout - place_id: {place_id}")
|
||||
raise CrawlingTimeoutException(f"Request timed out after {self.REQUEST_TIMEOUT}s")
|
||||
@@ -151,6 +168,29 @@ query getAccommodation($id: String!, $deviceType: String) {
|
||||
print(f"[NvMapScraper] Client error: {e}")
|
||||
raise GraphQLException(f"Client error: {e}")
|
||||
|
||||
async def _get_facility_string(self, place_id: str) -> str | None:
|
||||
"""숙소 페이지에서 편의시설 정보를 크롤링합니다.
|
||||
|
||||
Args:
|
||||
place_id: 네이버 지도 장소 ID
|
||||
|
||||
Returns:
|
||||
편의시설 정보 문자열 또는 None
|
||||
"""
|
||||
url = f"https://pcmap.place.naver.com/accommodation/{place_id}/home"
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url, headers=self._get_request_headers()) as response:
|
||||
soup = bs4.BeautifulSoup(await response.read(), "html.parser")
|
||||
c_elem = soup.find("span", "place_blind", string="편의")
|
||||
if c_elem:
|
||||
facilities = c_elem.parent.parent.find("div").string
|
||||
return facilities
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(f"[NvMapScraper] Failed to get facility info: {e}")
|
||||
return None
|
||||
|
||||
|
||||
# if __name__ == "__main__":
|
||||
# import asyncio
|
||||
|
||||
Reference in new issue
Block a user