inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[신규 개정판] 이것이 진짜 크롤링이다 - 실전편 (인공지능 수익화)

코레일 크롤링 질문

526

김남혁

작성한 질문수 1

0

코레일도 토요코인이랑 비슷하게 post 이용해서 크롤링하려 해봤는데 잘 안되더라고요,,

결국에는 그냥 selenium으로 들어가서 beautifulsoup로 좌석있는지 체크하고 10초마다 다시 조회한 다음 좌석있는지 다시 체크하는 식으로 해서 어느 정도 성공시키긴 했는데, 코레일은 requests랑 beautifulsoup만으로는 어려울까요?


import requests

from bs4 import BeautifulSoup

import time

token = ""
channel = "#test"
text = "Check your stock crawler."


def post_message(token, channel, text):

   requests.post("https://slack.com/api/chat.postMessage",

       headers={"Authorization": "Bearer "+token},

       data={"channel": channel,"text": text}

   )

 

myToken = "API토큰"

 

url = "https://www.letskorail.com/ebizprd/EbizPrdTicketpr21100W_pr21110.do"



#date_list = ['2022/06/25', '2022/07/02']

datas_obj = { 
    "selGoTrain": 5,
    "txtPsgFlg_1": 1,
    "txtPsgFlg_2": 0,
    "txtPsgFlg_8": 0,
    "txtPsgFlg_3": 0,
    "txtPsgFlg_4": 0,
    "txtPsgFlg_5": 0,
    "txtSeatAttCd_3": 000,
    "txtSeatAttCd_2": 000,
    "txtSeatAttCd_4": 15,
    "selGoTrainRa": 5,
    "radJobId": 1,
    "adjcCheckYn": "Y",
    "txtGoStart": "용산",
    "txtGoEnd": "전주",
    "txtGoStartCode": 104,
    "txtGoEndCode":45,
    "selGoYear": 2023,
    "selGoMonth":3,
    "selGoDay": 23,
    "selGoHour": 8,
    "txtGoHour": 85500,
    "txtGoYoil": "목",
    "selGoSeat1": 15,
    "txtPsgCnt1": 1,
    "txtPsgCnt2": 0,
    "txtGoPage": 1,
    "txtGoAbrdDt": 20230323,
    "checkStnNm": "Y",
    "txtMenuId": 11,
    "SeandYo": "N",
    "ra": 1,
    "hidRsvTpCd": 3,
    "txtPsgTpCd1": 1,
    "txtPsgTpCd2": 3,
    "txtPsgTpCd3": 1,
    "txtPsgTpCd5": 1,
    "txtPsgTpCd7": 1,
    "txtPsgTpCd8": 3,
    "txtDiscKndCd1": 000,
    "txtDiscKndCd2": 000,
    "txtDiscKndCd3": 111,
    "txtDiscKndCd5": 131,
    "txtDiscKndCd7": 112,
    "txtDiscKndCd8": 321,
    "txtCompaCnt1": 0,
    "txtCompaCnt2": 0,
    "txtCompaCnt3": 0,
    "txtCompaCnt4": 0,
    "txtCompaCnt5": 0,
    "txtCompaCnt6": 0,
    "txtCompaCnt7": 0,
    "txtCompaCnt8": 0

}


while True:
    time.sleep(2)
    response = requests.post(url, data=datas_obj)
    html = response.text
    soup = BeautifulSoup(html, 'html.parser')
    
    #a가 있으면 좌석 있음:#tableResult > tbody > tr:nth-child(1) > td:nth-child(6) > a:nth-child(1) > img
    #a없이 바로 이미지면 좌석 없음:#tableResult > tbody > tr:nth-child(1) > td:nth-child(6) > img
    # '#tableResult > tbody > tr:nth-child(1) > td:nth-child(6) > a:nth-child(1) > img' 선택자를 이용하여 좌석 이미지를 찾습니다.
    seat_with_a = soup.select_one('#tableResult > tbody > tr:nth-child(1) > td:nth-child(6) > a:nth-child(1) > img')
    seat_with_a2 = soup.select_one('#tableResult > tbody > tr:nth-child(3) > td:nth-child(6) > a:nth-child(1) > img')
#tableResult > tbody > tr:nth-child(3) > td:nth-child(6) > img
#tableResult > tbody > tr:nth-child(3) > td:nth-child(6) > a:nth-child(1) > img
    # '#tableResult > tbody > tr:nth-child(1) > td:nth-child(6) > img' 선택자를 이용하여 좌석 이미지를 찾습니다.
    seat_without_a = soup.select_one('#tableResult > tbody > tr:nth-child(1) > td:nth-child(6) > img')
    seat_without_a2 = soup.select_one("#tableResult > tbody > tr:nth-child(3) > td:nth-child(6) > img")

    # 좌석 이미지가 있으면 "좌석 있음"을, 없으면 "좌석 없음"을 출력합니다.
    if seat_with_a or seat_with_a2:
        print("좌석 있음")
        post_message(token, channel, "좌석 생김")
        
        
    elif seat_without_a and seat_without_a2:
        print("좌석 없음")

이렇게 했는데 데이터 자체가 잘못됐는지 중간에 print(html)로 보니까 제대로 해당 페이지를 가져온 것 같지도 않더라고요..

python 웹-크롤링

답변 1

0

스타트코딩

안녕하세요!

저도 해당 사이트 requests.post로 요청해본 결과

좌석정보를 제외한 html을 보내주네요.

 

실제 브라우저에서 보여지는 html은 약 5천줄인데, 응답받은 html 코드는 2천줄밖에 안됩니다.

다른 ajax요청이 있나 찾아봤는데 없네요.

내부적으로 html을 만들고 있는 사이트로 예상됩니다. (좀 더 확인해 보겠습니다)

 

실제로 클릭까지 진행되어야 하니

셀레니움으로 프로그램을 만드는 것이 어떨까요?ㅎㅎ

참고문서는 아래에 있습니다.

https://givemethesocks.tistory.com/65

 

 

셀레니움 환경설정 오류

0

48

2

네이버 로그인 관련

0

261

2

안녕하세요 셀레니움에 대해서 질문

0

85

1

크롤링 연습사이트 문의

0

97

2

선택자 질문

0

71

2

'특정 요소가 나타날 때까지 스크롤' 부분 에러

0

78

2

자동 로그인 질문

0

89

2

44강 제목, 링크

0

105

1

원하는 값이 없을 때

0

90

2

크롤링한 링크가 엑셀로 들어가면 작동이 안되요

0

227

2

셀레니움 PDF자료는 받을 수 있나요

0

100

2

글목록 추출하기

0

98

2

메일 자동화 로그인 중복방지문자해결 오류 및 명시적 대기 질문

0

88

2

강의 노트가 어디에 있는건가요?

0

80

2

강의 커리큘럼 질문

0

98

1

조건문 else 사용하지 않는 이유

0

76

2

셀레니움으로 접근할 수 없는 경우

0

95

2

웹페이지 변경

0

72

2

자바스크립트로 태그 선택 시 질문입니다.

1

64

2

수료증은 어떻게 받나요?

0

120

2

class명을 활용하여 선택자를 만들지 않는 경우..?

0

61

2

드라이버가 안 열려요

0

79

2

이거 해결방법 아시는 분?

0

121

2

네이버 지식인 크롤링..

0

202

2