이 문서에서는 Quora 데이터를 추출하는 방법과 이것이 유용한 이유, 그리고 이 작업을 자동화하는 데 Python을 사용하는 방법에 대해 중점적으로 설명합니다. 또한 이 사이트에서 스크랩하는 데 필요한 주요 도구와 라이브러리도 살펴봅니다.
Quora는 전 세계 사람들이 사용하는 가장 인기 있는 질문 답변 웹사이트 중 하나입니다. 특히 미국, 영국, 캐나다, 호주 및 기타 영어권 국가에서 두드러집니다. Quora 데이터를 분석하면 다음과 같은 많은 이점이 있습니다:
이 플랫폼은 연구, 콘텐츠 개발 또는 AI 솔루션 구축에 사용할 수 있습니다.
웹 스크래핑은 웹사이트나 웹 페이지에서 정보와 데이터를 추출하는 작업을 말합니다. 많은 정보를 수집하여 CSV 파일과 같은 체계적인 구조로 변환하는 현대적인 방법입니다.
웹 스크래핑이란 무엇인가 Quora 플랫폼에서 제공합니다:
따라서 Quora 데이터 스크래핑은 사용자 참여도, 중요도, 다양한 질문의 인기도 및 답변에 대한 인사이트를 제공합니다.
Quora 데이터를 스크랩하기 위해 Python 라이브러리가 사용됩니다. 다음은 이 목표를 달성하는 데 도움이 되는 가장 관련성이 높은 리소스입니다:
이러한 라이브러리를 사용하면 웹 페이지와 상호 작용하고 Quora에서 손쉽게 정보를 수집할 수 있습니다.
이 하위 섹션에서는 스크레이퍼의 구성에 대해 단계적으로 설명합니다. 작업 공간을 준비하고, 필요한 라이브러리를 설치하고, 요청을 보내고, HTML 코드를 구문 분석하고, 검색된 정보로 작업하기 위한 절차를 만듭니다.
스크래핑을 하려면 미리 작업 환경을 준비해야 합니다:
python -m venv quora_scraper
source quora_scraper/bin/activate # MacOS 및 Linux용
quora_scraper\Scripts\activate # Windows용
이 단계에서 웹 스크래핑에 필요한 라이브러리를 설치합니다:
pip install requests beautifulsoup4
이러한 인터페이스는 HTTP 요청을 전송하고 이후 수신된 HTML 데이터를 분석하는 데 필수적입니다.
특정 API를 호출하고 HTML 페이지를 다시 가져오기 위해 요청 라이브러리를 사용합니다. 직관적이며 매우 빠르게 작업을 완료할 수 있습니다.
url = "https://www.quora.com/How-do-you-open-your-own-company"
response = requests.get(url)
Python을 사용하여 Quora 답변을 스크랩하려면 BeautifulSoup이라는 또 다른 라이브러리가 필요합니다. 이 라이브러리를 설치하는 방법은 다음과 같습니다:
soup = BeautifulSoup(response.text, "lxml")
question = soup.find(class_='q-box qu-userSelect--text')
질문과 답변을 추출하려면 이러한 세부 정보가 포함된 필수 HTML 태그만 찾으면 됩니다. 사례를 들어 보겠습니다:
text_of_answers = []
for answer_id in range(6):
answers = soup.find_all(
class_=f'q-box dom_annotate_question_answer_item_{answer_id} qu-borderAll qu-borderColor--raised qu-boxShadow--small qu-mb--small qu-bg--raised')
for answer in answers:
text = answer.find('p', class_='q-text qu-display--block qu-wordBreak--break-word qu-textAlign--start')
text_of_answers.append(text)
Quora는 답변이 많은 경향이 있어 모든 답변을 보기 위해 페이지를 많이 스크롤해야 하는 경우가 많습니다. 이를 위해 Selenium을 사용하여 웹사이트를 자동화할 것입니다. 다음은 Selenium을 설정하고 프록시를 사용하여 신원을 더 잘 숨기는 방법입니다:
from selenium.webdriver.chrome.options import Options
from seleniumwire import webdriver as wiredriver
chrome_options = Options()
chrome_options.add_argument(f'--proxy-server={proxy_address}')
chrome_options.add_argument(f'--proxy-auth={proxy_username}:{proxy_password}')
chrome_options.add_argument("--headless")
driver = wiredriver.Chrome(options=chrome_options)
Selenium 에서 모든 것을 설정한 후에는 HTTP 요청을 한 다음 계속 아래로 스크롤하여 이러한 데이터 조각을 캡처하기만 하면 됩니다:
url = "https://www.quora.com/How-do-you-open-your-own-company"
driver.execute_script('window.scrollBy(0, 1000)')
driver.get(url)
데이터 수집이 끝나면 나중에 분석하기 쉬운 방식으로 데이터를 보관하고 싶을 것입니다. 이를 위한 가장 좋은 방법은 가장 널리 사용되는 JSON 형식으로 보관하는 것입니다.
with open(f'quora_data.json', 'w', encoding='utf-8') as json_file:
json.dump(text_of_answers, json_file, ensure_ascii=False, indent=4)
데이터를 JSON으로 저장했지만, 경우에 따라 한 번에 두 가지 이상의 형식으로 저장하고 싶을 수도 있습니다. 그래서 여기에 바로 이 작업을 수행하는 함수가 있습니다:
def export_data(data, csv_filename="quora_data.csv", json_filename="quora_data.json"):
save_to_csv(data, csv_filename)
save_to_json(data, json_filename)
export_data(text_of_answers)
Quora에는 자동 데이터 스크래핑에 대한 몇 가지 방어 기능이 있으므로 Quora에 많은 요청을 보내려고 하면 IP 주소가 차단될 수 있습니다. 하지만 이를 우회하는 방법이 있습니다.
이는 요청이 전송될 때 일정한 형태의 지연을 추가하는 기본적인 인간 행동 모방입니다.
import time
import random
def random_delay():
time.sleep(random.uniform(2, 5))
차단되지 않을 확률을 높이려면 모든 쿼리 후에 이 기능을 추가하세요.
프록시 서버를 사용하면 IP 주소 차단을 쉽게 피할 수 있습니다. Requests 및 Selenium 에서 어떻게 사용할 수 있는지 살펴보겠습니다.
url = "https://www.quora.com/How-do-you-open-your-own-company"
proxy = 'LOGIN:PASSWORD@ADDRESS:PORT'
proxies = {
"http": f"http://{proxy}",
"https": f"https://{proxy}",
}
response = requests.get(url, proxies=proxies)
proxy_address = ""
proxy_username = ""
proxy_password = ""
chrome_options = Options()
chrome_options.add_argument(f'--proxy-server={proxy_address}')
chrome_options.add_argument(f'--proxy-auth={proxy_username}:{proxy_password}')
chrome_options.add_argument("--headless")
driver = wiredriver.Chrome(options=chrome_options)
따라서 모든 단계를 다룬 후에는 이를 결합하여 하나의 스크립트에 넣을 차례입니다.
import json
from selenium.webdriver.chrome.options import Options
from seleniumwire import webdriver as wiredriver
from bs4 import BeautifulSoup
proxy_address = ""
proxy_username = ""
proxy_password = ""
chrome_options = Options()
chrome_options.add_argument(f'--proxy-server={proxy_address}')
chrome_options.add_argument(f'--proxy-auth={proxy_username}:{proxy_password}')
chrome_options.add_argument("--headless")
driver = wiredriver.Chrome(options=chrome_options)
url = "https://www.quora.com/How-do-you-open-your-own-company"
driver.execute_script('window.scrollBy(0, 1000)')
driver.get(url)
html = driver.page_source
soup = BeautifulSoup(html, "lxml")
question = soup.find(class_='q-box qu-userSelect--text')
# 답변
text_of_answers = [{'question': question}]
for answer_id in range(6):
answers = soup.find_all(
class_=f'q-box dom_annotate_question_answer_item_{answer_id} qu-borderAll qu-borderColor--raised qu-boxShadow--small qu-mb--small qu-bg--raised')
for answer in answers:
text = answer.find('p', class_='q-text qu-display--block qu-wordBreak--break-word qu-textAlign--start').text
text_of_answers.append({
'answers': text,
})
with open(f'Quora_data.json', 'w', encoding='utf-8') as json_file:
json.dump(text_of_answers, json_file, ensure_ascii=False, indent=4)
print(f"Quora_data.json")
이 문서에서는 Python을 사용한 Quora 스크래핑 방법에 대해 설명했습니다. 이렇게 구성된 스크립트를 통해 사용자는 페이지 매김과 함께 일부 제한을 재정의하고 JSON 및 CSV와 같은 다양한 형식으로 데이터를 저장할 수 있습니다.
대규모 데이터 수집의 경우, 가장 효과적인 방법은 Quora의 API를 사용하는 것입니다. 반면에 전략적으로 BeautifulSoup 또는 Selenium을 활용하기로 선택한 경우에는 지속적인 성능을 위해 프록시 서버를 사용하는 것이 필수입니다.
댓글: 0