안녕하세요, Crawlee 개발자 여러분. Crawlee 블로그의 또 다른 튜토리얼에 다시 오신 것을 환영합니다. 이 튜토리얼에서는 Python용 Crawlee를 사용하여 무한 스크롤 웹사이트를 스크랩하는 방법을 알려드립니다.
문맥상 무한 스크롤 페이지는 기존 페이지 매김에 대한 현대적인 대안입니다. 사용자가 다음 페이지를 선택하는 대신 웹페이지 하단으로 스크롤하면 페이지가 자동으로 더 많은 데이터를 로드하고 사용자는 더 많이 스크롤할 수 있습니다.
나는 큰 운동화광으로서 나이키 신발 무한 스크롤 웹사이트를 예로 들어 여기에서 수천 개의 운동화를 긁어낼 것입니다.
Python용 Crawlee에는 HTTP 및 헤드리스 브라우저 크롤링을 위한 통합 인터페이스, 자동 재시도 등 몇 가지 놀라운 초기 기능이 있습니다.
프로젝트 전제조건 및 부트스트래핑
다음 명령을 사용하여 Python용 Crawlee를 설치하여 튜토리얼을 시작하겠습니다.
pipx run crawlee create nike-crawler
로그인 후 복사
계속 진행하기 전에 이 블로그를 읽고 싶으시면 GitHub에서 Crawlee for Python에 별점을 주시면 정말 기쁠 것입니다!
애피파이
/
크롤리 파이썬
Crawlee - 안정적인 크롤러를 구축하기 위한 Python용 웹 스크래핑 및 브라우저 자동화 라이브러리입니다. AI, LLM, RAG 또는 GPT에 대한 데이터를 추출합니다. 웹사이트에서 HTML, PDF, JPG, PNG 및 기타 파일을 다운로드하세요. BeautifulSoup, Playwright 및 원시 HTTP와 함께 작동합니다. 헤드풀 모드와 헤드리스 모드 모두. 프록시 회전 포함.
웹 스크래핑 및 브라우저 자동화 라이브러리
Crawlee는 크롤링과 스크래핑을 처음부터 끝까지 다루고 신뢰할 수 있는 스크래퍼를 구축하도록 도와줍니다. 빠릅니다.
? Python용 Crawlee는 얼리 어답터에게 열려 있습니다!
크롤러는 기본 구성을 사용해도 거의 인간과 비슷하게 보이며 최신 봇 보호의 레이더를 피해 날아갑니다. Crawlee는 기술적 세부 사항에 대해 걱정할 필요 없이 웹에서 링크를 크롤링하고, 데이터를 스크랩하고, 기계가 읽을 수 있는 형식으로 지속적으로 저장할 수 있는 도구를 제공합니다. 그리고 풍부한 구성 옵션 덕분에 기본 설정으로 충분하지 않은 경우 Crawlee의 거의 모든 측면을 프로젝트 요구 사항에 맞게 조정할 수 있습니다.
? Crawlee 프로젝트 웹사이트에서 전체 문서, 가이드 및 예제 보기 ?
또한 프로젝트에 탐색하고 활용할 수 있는 Crawlee의 TypeScript 구현도 있습니다. GitHub의 JS/TS용 Crawlee에 대한 자세한 내용을 보려면 GitHub 저장소를 방문하세요.
설치
우리는…
GitHub에서 보기
We will scrape using headless browsers. Select PlaywrightCrawler in the terminal when Crawlee for Python asks for it.
After installation, Crawlee for Python will create boilerplate code for you. Redirect into the project folder and then run this command for all the dependencies installation:
poetry install
로그인 후 복사
How to scrape infinite scrolling webpages
Handling accept cookie dialog
Adding request of all shoes links
Extract data from product details
Accept Cookies context manager
Handling infinite scroll on the listing page
Exporting data to CSV format
Handling accept cookie dialog
After all the necessary installations, we'll start looking into the files and configuring them accordingly.
When you look into the folder, you'll see many files, but for now, let’s focus on main.py and routes.py.
In __main__.py, let's change the target location to the Nike website. Then, just to see how scraping will happen, we'll add headless = False to the PlaywrightCrawler parameters. Let's also increase the maximum requests per crawl option to 100 to see the power of parallel scraping in Crawlee for Python.
As the cookie dialog is blocking us from crawling more than one page's worth of shoes, let’s get it out of our way.
We can handle the cookie dialog by going to Chrome dev tools and looking at the test_id of the "accept cookies" button, which is dialog-accept-button.
Now, let’s remove the context.push_data call that was left there from the project template and add the code to accept the dialog in routes.py. The updated code will look like this:
from crawlee.router import Router
from crawlee.playwright_crawler import PlaywrightCrawlingContext
router = Router[PlaywrightCrawlingContext]()
@router.default_handler
async def default_handler(context: PlaywrightCrawlingContext) -> None:
# Wait for the popup to be visible to ensure it has loaded on the page.
await context.page.get_by_test_id('dialog-accept-button').click()
로그인 후 복사
Adding request of all shoes links
Now, if you hover over the top bar and see all the sections, i.e., man, woman, and kids, you'll notice the “All shoes” section. As we want to scrape all the sneakers, this section interests us. Let’s use get_by_test_id with the filter of has_text=’All shoes’ and add all the links with the text “All shoes” to the request handler. Let’s add this code to the existing routes.py file:
shoe_listing_links = (
await context.page.get_by_test_id('link').filter(has_text='All shoes').all()
)
await context.add_requests(
[
Request.from_url(url, label='listing')
for link in shoe_listing_links
if (url := await link.get_attribute('href'))
]
)
@router.handler('listing')
async def listing_handler(context: PlaywrightCrawlingContext) -> None:
"""Handler for shoe listings."""
로그인 후 복사
Extract data from product details
Now that we have all the links to the pages with the title “All Shoes,” the next step is to scrape all the products on each page and the information provided on them.
We'll extract each shoe's URL, title, price, and description. Again, let's go to dev tools and extract each parameter's relevant test_id. After scraping each of the parameters, we'll use the context.push_data function to add it to the local storage. Now let's add the following code to the listing_handler and update it in the routes.py file:
Since we're dealing with multiple browser pages with multiple links and we want to do infinite scrolling, we may encounter an accept cookie dialog on each page. This will prevent loading more shoes via infinite scroll.
We'll need to check for cookies on every page, as each one may be opened with a fresh session (no stored cookies) and we'll get the accept cookie dialog even though we already accepted it in another browser window. However, if we don't get the dialog, we want the request handler to work as usual.
To solve this problem, we'll try to deal with the dialog in a parallel task that will run in the background. A context manager is a nice abstraction that will allow us to reuse this logic in all the router handlers. So, let's build a context manager:
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
@asynccontextmanager
async def accept_cookies(page: Page):
task = asyncio.create_task(page.get_by_test_id('dialog-accept-button').click())
try:
yield
finally:
if not task.done():
task.cancel()
with suppress(asyncio.CancelledError, PlaywrightTimeoutError):
await task
로그인 후 복사
This context manager will make sure we're accepting the cookie dialog if it exists before scrolling and scraping the page. Let’s implement it in the routes.py file, and the updated code is here
Handling infinite scroll on the listing page
Now for the last and most interesting part of the tutorial! How to handle the infinite scroll of each shoe listing page and make sure our crawler is scrolling and scraping the data constantly.
To handle infinite scrolling in Crawlee for Python, we just need to make sure the page is loaded, which is done by waiting for the network_idle load state, and then use the infinite_scroll helper function which will keep scrolling to the bottom of the page as long as that makes additional items appear.
Let’s add two lines of code to the listing handler:
As we want to store all the shoe data into a CSV file, we can just add a call to the export_data helper into the __main__.py file just after the crawler run:
await crawler.export_data('shoes.csv')
로그인 후 복사
Working crawler and its code
Now, we have a crawler ready that can scrape all the shoes from the Nike website while handling infinite scrolling and many other problems, like the cookies dialog.
You can find the complete working crawler code here on the GitHub repository.
If you have any doubts regarding this tutorial or using Crawlee for Python, feel free to join our discord community and ask fellow developers or the Crawlee team.
Crawlee & Apify
This is the official developer community of Apify and Crawlee. | 8365 members
discord.com
This tutorial is taken from the webinar held on August 5th where Jan Buchar, Senior Python Engineer at Apify, gave a live demo about this use case. Watch the whole webinar here.
위 내용은 Python으로 무한 스크롤 웹페이지를 긁는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Python은 배우고 사용하기 쉽고 C는 더 강력하지만 복잡합니다. 1. Python Syntax는 간결하며 초보자에게 적합합니다. 동적 타이핑 및 자동 메모리 관리를 사용하면 사용하기 쉽지만 런타임 오류가 발생할 수 있습니다. 2.C는 고성능 응용 프로그램에 적합한 저수준 제어 및 고급 기능을 제공하지만 학습 임계 값이 높고 수동 메모리 및 유형 안전 관리가 필요합니다.
제한된 시간에 Python 학습 효율을 극대화하려면 Python의 DateTime, Time 및 Schedule 모듈을 사용할 수 있습니다. 1. DateTime 모듈은 학습 시간을 기록하고 계획하는 데 사용됩니다. 2. 시간 모듈은 학습과 휴식 시간을 설정하는 데 도움이됩니다. 3. 일정 모듈은 주간 학습 작업을 자동으로 배열합니다.
Python은 개발 효율에서 C보다 낫지 만 C는 실행 성능이 높습니다. 1. Python의 간결한 구문 및 풍부한 라이브러리는 개발 효율성을 향상시킵니다. 2.C의 컴파일 유형 특성 및 하드웨어 제어는 실행 성능을 향상시킵니다. 선택할 때는 프로젝트 요구에 따라 개발 속도 및 실행 효율성을 평가해야합니다.
하루에 2 시간 동안 파이썬을 배우는 것으로 충분합니까? 목표와 학습 방법에 따라 다릅니다. 1) 명확한 학습 계획을 개발, 2) 적절한 학습 자원 및 방법을 선택하고 3) 실습 연습 및 검토 및 통합 연습 및 검토 및 통합,이 기간 동안 Python의 기본 지식과 고급 기능을 점차적으로 마스터 할 수 있습니다.
Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.
Pythonlistsarepartoftsandardlardlibrary, whileraysarenot.listsarebuilt-in, 다재다능하고, 수집 할 수있는 반면, arraysarreprovidedByTearRaymoduledlesscommonlyusedDuetolimitedFunctionality.
파이썬은 자동화, 스크립팅 및 작업 관리가 탁월합니다. 1) 자동화 : 파일 백업은 OS 및 Shutil과 같은 표준 라이브러리를 통해 실현됩니다. 2) 스크립트 쓰기 : PSUTIL 라이브러리를 사용하여 시스템 리소스를 모니터링합니다. 3) 작업 관리 : 일정 라이브러리를 사용하여 작업을 예약하십시오. Python의 사용 편의성과 풍부한 라이브러리 지원으로 인해 이러한 영역에서 선호하는 도구가됩니다.
웹 개발에서 Python의 주요 응용 프로그램에는 Django 및 Flask 프레임 워크 사용, API 개발, 데이터 분석 및 시각화, 머신 러닝 및 AI 및 성능 최적화가 포함됩니다. 1. Django 및 Flask 프레임 워크 : Django는 복잡한 응용 분야의 빠른 개발에 적합하며 플라스크는 소형 또는 고도로 맞춤형 프로젝트에 적합합니다. 2. API 개발 : Flask 또는 DjangorestFramework를 사용하여 RESTFULAPI를 구축하십시오. 3. 데이터 분석 및 시각화 : Python을 사용하여 데이터를 처리하고 웹 인터페이스를 통해 표시합니다. 4. 머신 러닝 및 AI : 파이썬은 지능형 웹 애플리케이션을 구축하는 데 사용됩니다. 5. 성능 최적화 : 비동기 프로그래밍, 캐싱 및 코드를 통해 최적화