首先创建项目 scrapy startproject Dongguan,用pycharm打开项目Dongguan
cd到Dongguan项目文件夹,创建规则爬虫 scrapy genspider -t crawl dongguan(爬虫名称) wz.sun0769.com(爬取网页的范围)
在文件夹中创建创建start.py文件,直接运行start .py 文件就可以跑起项目
from scrapy import cmdline
#导包
cmdline.execute('scrapy crawl dongguan -o dongguan.csv'.split())
#dongguan是你创建的爬虫名字,dongguan.csv为爬取内容的保存路径
csv为保存格式, scrapy中还有其他6中保存格式 ('marshal', 'pickle','jsonlines', 'json', 'xml')
在spider文件夹下的dongguan.py中写爬取政务网站的函数
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from Dongguan.items import DongguanItemname = 'dongguan'
#爬虫名称
allowed_domains = ['wz.sun0769.com']
#爬虫爬取网页的范围
start_urls = ['http://wz.sun0769.com/index.php/question/questionType?type=4&page=']
#爬虫爬取的数据的起始页
rules = (Rule(LinkExtractor(allow=r'type=4&page=\d+'),follow=True),
#列表页的爬取规则page=\d+,起始页为page=30,以后以此累加,提取共同部分
Rule(LinkExtractor(allow=r'question/\d+/\d+\.shtml'), callback='parse_item', follow=True),
#设置详情页爬取规则\d+表示0-9的数字1个或一个以上,每个详情页的url为http://wz.sun0769.com/html/question/201807/378767.shtml, call_back为回调给的函数,follow为True表示爬取爬取所有的符合规则的网页
)
#爬取的规则函数
def parse_item(self, response):item = DongguanItem()
#实例化DongguanItem一个类
url=response.urlquestion_title=response.xpath('//div[@class="pagecenter p3"]/div/div/div/strong/text()').extract()
#使用Xpath获取标题内容
#注意此处要使用scrapy中的extract(),不能使用get()方法
if len(question_title)>0:
#判断详情页中是否有内容,有的话获取内容
title_name=question_title[0].split('\xa0\xa0')[0][4:]
#截取标题[4:]表示从字符串第4位截取,[0]表示取截取的前部分
title_number=question_title[0].split('\xa0\xa0')[1][3:]item['title_name'] = title_name
#创建字典,{'title_name':'每个详情的标题'}
item['title_number'] = title_numberquestion_content=response.xpath('//div[@class="c1 text14_2"]/text()|//div[@class="contentext"]/text()').extract()
#使用Xpath截取详情页反馈的内容
if len(question_content)>0:
question_content=question_content[0].strip()yield item
#使用生成器,返回item
注册items文件中的DongguanItem()类,注册爬取的字段
#在spider文件夹中的items中注册爬取字段
import scrapy
#导包
class DongguanItem(scrapy.Item):question_content=scrapy.Field()
#注意字段必须要与item[' ']中引号的名字相同