(1)创建scrapy项目并创建爬虫。
我用的是pycharm,在终端框输入scrapy startproject hbdt创建名字为hbdt的项目。接着输入scrapy genspider rw1 news.hbtv.com.cn创建名为rw1的爬虫。
(2)目标
我的目标是筛选湖北网台10月后所有标题带关键词为军运或者军人运动会的新闻,然后进入关键词所在新闻的url,下载它的题目和新闻内容。
(3)编写爬虫代码
# -*- coding: utf-8 -*-
import scrapy
class Rw1Spider(scrapy.Spider):
name = 'rw1'
allowed_domains = ['news.hbtv.com.cn']
start_urls = ['http://news.hbtv.com.cn/hbxw1072?page=1']
def parse(self, response):
j1s = response.xpath("//a[@class='headers']/text()").extract()
i = 0
for j1 in j1s:
if '军运' in str(j1) or '军人运动会' in str(j1):
content_url = response.xpath("//section[@class='ov']//li//h3/a/@href").extract()[i]
content_url = "http://news.hbtv.com.cn"