这是我参与更文挑战的第13天,活动详情查看: 更文挑战
3 爬虫初始化
也就是上面标红的两条线
$ cd mySpider
$ scrapy genspider example example.com(要爬取的网页url)
初始化后的程序与目录结构如下:
4 在items.py中编写我们想要获得的字段
import scrapy
class ChinanewsItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
#站点名
sourceName = scrapy.Field()
#站点地址
sourceUrl = scrapy.Field()
#文章地址
articleUrl = scrapy.Field()
#标题
title = scrapy.Field()
#发布时间
publishTime = scrapy.Field()
#文章分类
articleCategory = scrapy.Field()
#文章标签
articalLabel = scrapy.Field()
#文章内容
articleContent = scrapy.Field()
5 获取我们要爬取网页链接
在实验中我们要爬取的页面(静态页面)为中国新闻网 爬取规则:
滚动新闻:http://域名/scroll-news/年/月日/news.shtml ,例如:www.chinanews.com/scroll-news…
某个分类下的新闻:http://域名/scroll-news/分类对应的网站文件夹/年/月日/news.shtml,例如:http://www.chinanews.com/cul/2021/06-15/9500187.shtml cul为文化(culture)分类下的新闻
在网页中通过右击检查或者F12,找出我们所需要的url链接。
现在想要获取这个<a标签里的url地址,
hrefs = response.xpath("//div[@class='content_list']//div[@class='dd_bt']/a/@href").extract()
- div[@class='content_list']找类型是content_list的class
- div[@class='dd_bt']再找content_list下类型为dd_bt的class
- /a/@href"再找a标签下的属性标签
- 通过.extract()抽取出url
6 运行爬虫
$ scrapy crwal news
爬虫结果:
从上面可以看出,我们现在已经能获得不同日期的滚动新闻的链接。
7 通过获得的链接,再次发送url,获得新闻详情页面数据
通过爬虫获得标题。
item['title'] = response.xpath("//h1/text()").extract()[0].strip()
extract()[0]提取出列表中第一项,.strip()去除空格