FreeShare

Tạo cron job crawler dữ liệu website sử dụng scrapy

Chủ nhật, 18/02/2024
image
Viết 1 spider crawler web bạn có thể tham khảo tại docs này Ví dụ code về crawler trang vnexpress Ví dụ về crawler trang render client như các trang sử dụng reactjs, vuejs. ở đây ta cần sử dụng thư viện scrapy-splash để snapshot lại các dữ liệu hiện thị trên trang Bạn có

Viết 1 spider crawler web bạn có thể tham khảo tại docs này

Ví dụ code về crawler trang vnexpress

# _*_ coding: utf8 _*_
# !/usr/bin/env python
__author__ = 'TranTien'


import scrapy
from scrapy.http import Request
from crawl_scrapy.helper.init_config import LoadConfig
from crawl_scrapy.helper.parser_detail import ParserDetail


class Vnexpress(scrapy.Spider):
    name = 'vnexpress'
    allowed_domain = ['vnexpress.net']

    def __init__(self):
        self.config = LoadConfig('vnexpress.net')
        print(self.config, "self.config")

    def start_requests(self):
        urls = [
            'https://vnexpress.net/'
        ]
        for url in urls:
            yield Request(url, self.parse)

    def parse(self, response):
        try:
            post_urls = response.selector.xpath(self.config.category_link).extract()
            for url in post_urls:
                meta = {'url': url}
                yield Request(url, callback=self.parse_full_post, meta=meta, method='get')
        except Exception as e:
            print('co loi xay ra khi lay link bai viet', e)

    def parse_full_post(self, response):
        ParserDetail(response, self.config)

Ví dụ về crawler trang render client như các trang sử dụng reactjs, vuejs. ở đây ta cần sử dụng thư viện scrapy-splash để snapshot lại các dữ liệu hiện thị trên trang

import scrapy
from scrapy_splash import SplashRequest
from crawl_scrapy.helper.init_config import LoadConfig

class Livescores(scrapy.Spider):
    name = 'livescores'
    allowed_domain = ['livescores.com']

    def __init__(self):
        self.config = LoadConfig('livescores.com')

    def start_requests(self):
        url = 'https://livescores.com'

        splash_args = {
            'html': 1,
            'png': 1,
            'width': 600,
            'render_all': 1,
        }

        yield SplashRequest(url, self.parse_result, endpoint='render.json', args=splash_args)

    def parse_result(self, response):
        try:
            print("-------------------------------------------------------------------------")
            post_titles = response.selector.xpath(self.config.title).extract()
            for item in post_titles:
                print(item)
            print("-------------------------------------------------------------------------")
        except Exception as e:
            print('error :' , e)

Bạn có thể download source code tại đây