scrapy爬取百度热榜

64 阅读1分钟

1、安装scrapy

 pip install scrapy

2、创建scapy项目

scrapy startproject scrapyBaiduProject

 控制台出现下列信息则证明新建项目成功

​编辑

3、编写爬取解析的Spider

百度热榜的地址是: top.baidu.com/board?tab=r…

我们进入项目并创建爬取的Spider

cd .\scrapyBaiduProject\
scrapy genspider baidu https://top.baidu.com/board?tab=realtime

然后再spiders文件夹下就多了一个 baidu.py。这里面主要写我们的解析逻辑

​编辑

我们看一下百度热榜的html源码

​编辑通过html源码我们可以写出解析的代码

import scrapy


class BaiduSpider(scrapy.Spider):
    name = "baidu"
    allowed_domains = ["top.baidu.com"]
    start_urls = ["https://top.baidu.com/board?tab=realtime"]

    def parse(self, response):
        hotList = response.xpath('//div[starts-with(@class, "category-wrap_")]')
        for hot in hotList:
            link = hot.xpath('.//a[starts-with(@class, "title_")]/@href').extract_first()
            title = hot.xpath('.//a[starts-with(@class, "title_")]//div/text()').extract_first().strip()
            extra = hot.xpath('.//div[starts-with(@class, "hot-index_")]/text()').extract_first().strip()
            print('link:',link)
            print('title:',title)
            print('extra:',extra)

4、运行爬虫

scrapy crawl baidu

​编辑

这样我们的百度热榜数据简单爬取就完成了。