파이썬과 셀레늄으로 트위터 트윗 스크랩하기
스크랩된 데이터 예시
{
"type": "tweet",
"id": 1843447413824209200,
"viewCount": "51275823",
"url": "https://x.com/elonmusk/status/1843447413824209160",
"twitterUrl": "https://twitter.com/elonmusk/status/1843447413824209160",
"text": "It is a surefire way for the Dems to turn America in a one-party state, just like California",
"isQuote": true,
"retweetCount": 59493,
"replyCount": 11090,
"likeCount": 250068,
"quoteCount": 1661,
"createdAt": "Tue Oct 08 00:24:47 +0000 2024",
"lang": "en",
"quoteId": "1843379457605939258",
"bookmarkCount": 11177,
"isReply": false,
"source": "Twitter for iPhone",
"author": {
"type": "user",
"username": "elonmusk",
"url": "https://x.com/elonmusk",
"twitterUrl": "https://x.com/elonmusk",
"id": "44196397",
"name": "Elon Musk",
"isVerified": false,
"isBlueVerified": true,
"verifiedType": "",
"profilePicture": "https://pbs.twimg.com/profile_images/1849727333617573888/HBgPUrjG_normal.jpg",
"coverPicture": "https://pbs.twimg.com/profile_banners/44196397/1726163678",
"description": "Read @America to understand why I’m supporting Trump for President",
"location": "",
"followers": 202400789,
"following": 794,
"protected": false,
"status": "",
"canDm": false,
"canMediaTag": false,
"createdAt": "Tue Jun 02 20:12:29 +0000 2009",
"advertiserAccountType": "",
"analyticsType": "",
"entities": {
"description": {
"urls": []
},
"url": {
"urls": [
{
"display_url": "TheAmericaPAC.org",
"expanded_url": "http://TheAmericaPAC.org",
"url": "https://t.co/DjyKIO6ePx",
"indices": [
0,
23
]
}
]
}
},
"fastFollowersCount": 0,
"favouritesCount": 83676,
"geoEnabled": false,
"hasCustomTimelines": true,
"hasExtendedProfile": false,
"isTranslator": false,
"mediaCount": 2637,
"profileBackgroundColor": "",
"statusesCount": 55447,
"translatorTypeEnum": "",
"withheldInCountries": [],
"affiliatesHighlightedLabel": {
"label": {
"url": {
"url": "https://twitter.com/X",
"urlType": "DeepLink"
},
"badge": {
"url": "https://pbs.twimg.com/profile_images/1683899100922511378/5lY42eHs_bigger.jpg"
},
"description": "X",
"userLabelType": "BusinessLabel",
"userLabelDisplayType": "Badge"
}
}
},
"quote": {
"type": "tweet",
"id": "1843379457605939258",
"text": "Elon Musk explains how this will be our last real election if Kamala Harris wins.\n\nEveryone must watch this. https://t.co/DoBh9qM7K7",
"retweetCount": 10725,
"replyCount": 1848,
"likeCount": 38268,
"quoteCount": 790,
"createdAt": "Mon Oct 07 19:54:45 +0000 2024",
"lang": "en",
"bookmarkCount": 5143,
"author": {
"type": "user",
"username": "EndWokeness",
"url": "https://x.com/EndWokeness",
"twitterUrl": "https://x.com/EndWokeness",
"id": "1552795969959636992",
"name": "End Wokeness",
"isVerified": false,
"isBlueVerified": true,
"verifiedType": "",
"profilePicture": "https://pbs.twimg.com/profile_images/1563691268793946117/OedvhFeS_normal.jpg",
"coverPicture": "https://pbs.twimg.com/profile_banners/1552795969959636992/1720913469",
"description": "Fighting, exposing, and mocking wokeness. DM for submissions",
"location": "",
"followers": 3107102,
"following": 1177,
"protected": false,
"status": "",
"canDm": true,
"canMediaTag": true,
"createdAt": "Thu Jul 28 23:20:28 +0000 2022",
"advertiserAccountType": "",
"analyticsType": "",
"entities": {
"description": {
"urls": []
}
},
"fastFollowersCount": 0,
"favouritesCount": 13138,
"geoEnabled": false,
"hasCustomTimelines": true,
"hasExtendedProfile": false,
"isTranslator": false,
"mediaCount": 7219,
"profileBackgroundColor": "",
"statusesCount": 15502,
"translatorTypeEnum": "",
"withheldInCountries": [],
"affiliatesHighlightedLabel": {}
}
}
}
설정 없이 코드 직접 실행하기
본 가이드는 트위터 트윗 데이터를 원활하게 스크랩할 수 있는 완전한 코드 제공! 파이썬과 셀레늄으로 데이터 수집을 자동화하고 성능 로그를 효율적으로 캡처하세요. 추가 설정 없이 트위터 통찰력을 얻으세요!
고급 트윗 필터링
트위터의 고급 검색 기능을 활용하여 특정 기준에 맞는 트윗을 타겟팅하세요. 키워드, 날짜 및 해시태그로 필터링하여 관련 있고 집중된 데이터를 수집할 수 있습니다.
1단계: 환경 설정하기
먼저 셀레늄을 설치하여 브라우저 작업을 자동화합니다:
pip install -r requirements.txt
2단계: ChromeDriver 다운로드
여기에서 해당 ChromeDriver를 찾을 수 있습니다: ChromeDriver 다운로드
3단계: 테스트를 위한 Chrome 실행
이 단계는 효과를 보기 위한 디버깅용입니다. 원하지 않으면 이 단계를 건너뛸 수 있습니다.
@echo off
start C:\software\chrome-win64\chrome.exe --remote-debugging-port=9223
4단계: Chrome 옵션 설정하기
self.options = webdriver.ChromeOptions()
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
self.options.add_argument(f'user-agent={user_agent}')
self.options.add_argument('--disable-gpu')
self.options.add_argument('--no-sandbox')
self.options.add_argument('--disable-dev-shm-usage')
self.options.add_experimental_option("debuggerAddress", "localhost:9223")
js_script_name = modify_random_canvas_js()
self.browser = self.get_browser(script_files=[js_script_name], record_network_log=True, headless=True)
5단계: Selenium을 사용하여 트윗 데이터 검색하기
self.browser.switch_to.new_window('tab')
url = "https://x.com/explore"
self.browser.get(url=url)
search_box = self.browser.find_element(By.CSS_SELECTOR, '[data-testid="SearchBox_Search_Input"]')
search_box.send_keys(Keys.CONTROL + "a") # 모든 텍스트 선택
search_box.send_keys(Keys.DELETE)
self.browser.implicitly_wait(20)
search_box.send_keys(search_query)
# 검색 제출을 위해 Enter 키를 누릅니다.
search_box.send_keys(Keys.RETURN)
self.browser.implicitly_wait(1000)
second_div = self.browser.find_element(By.CSS_SELECTOR,'[data-testid="ScrollSnap-List"] [role="presentation"]:nth-of-type(2)')
6단계: 브라우저 네트워크 응답 모니터링
performance_log = self.browser.get_log("performance")
for packet in performance_log:
msg = packet.get("message")
message = json.loads(packet.get("message")).get("message")
packet_method = message.get("method")
if "Network" in packet_method and 'SearchTimeline' in msg:
document_url = message['params'].get('documentURL')
if (not document_url) or ('&f=live' not in document_url):
continue
request_id = message.get("params").get("requestId")
7단계: 응답에서 데이터 추출하기
entries = json.loads(body)['data']['search_by_raw_query']['search_timeline']['timeline']['instructions'][0].get('entries', '')
if not entries:
continue
for entry in entries:
item_content = entry['content'].get('itemContent', '')
if not item_content:
continue
tweet_result = entry['content']['itemContent']['tweet_results']['result']
entry_id = entry['entryId']
8단계: 중요한 고려사항
- 트위터에 로그인한 후 트위터 쿠키를 가져오세요. 트위터 쿠키 가져오는 방법 알아보기
- Apify의 API를 사용할 수 있습니다.
- GitHub에서 전체 코드를 받을 수 있습니다.
- 우리의 토론 그룹에 참여하세요! 여기를 클릭하세요
자주 묻는 질문(FAQ)
- Q: 파이썬과 셀레늄으로 트위터 스크래핑이란 무엇인가요?
트위터 스크래핑은 파이썬과 셀레늄과 같은 자동화 도구를 사용하여 트위터에서 데이터를 수집하는 과정입니다. 이러한 도구를 통해 브라우저를 시뮬레이션하고 트윗을 검색하며 정보를 수집할 수 있습니다.
- Q: 왜 트위터 데이터를 스크랩하고 싶나요?
트위터 데이터를 스크랩하면 연구를 위한 정보를 수집하거나 특정 주제를 추적하거나 트렌드를 분석할 수 있습니다. 이는 학생, 기업 및 공공 의견과 토론을 이해하고자 하는 모든 사람에게 유용합니다.
- Q: ChromeDriver란 무엇이며 왜 필요하나요?
ChromeDriver는 셀레늄과 구글 크롬 간의 번역기와 같습니다. 셀레늄이 크롬 브라우저와 상호작용하는 방법을 이해하도록 도와줍니다. 셀레늄이 버튼 클릭이나 정보 입력과 같은 작업을 자동화할 수 있도록 필요합니다.
- Q: 스크래핑에서 성능 로그란 무엇인가요?
성능 로그는 웹 스크래핑 중에 발생하는 모든 일을 기록하는 일기와 같습니다. 스크래퍼(셀레늄)와 트위터 페이지 간의 모든 데이터 교환을 추적하여 프로그램이 어떤 요청을 하는지 이해하는 데 도움을 줍니다.
- Q: 브라우저를 보지 않고 스크래핑 스크립트를 실행할 수 있나요?
네, '헤드리스' 모드에서 스크립트를 실행할 수 있으며, 이 경우 브라우저는 백그라운드에서 작동하여 화면에 보이지 않습니다.
- Q: 트위터를 스크래핑하기 위해 필요한 도구가 있나요?
네, 컴퓨터에 파이썬이 설치되어 있어야 하며, 셀레늄 라이브러리와 ChromeDriver도 필요합니다. 이 도구들을 함께 사용하면 웹 브라우저를 제어하고 원하는 데이터를 캡처할 수 있습니다.