首页 > 学院 > 开发设计 > 正文

实战 使用scrapy 爬取代理 并保存到数据库

2019-11-06 07:18:51
字体:
来源:转载
供稿:网友

   爬取网站: www.PRoxy360.com

   爬取思路: 1.分析首页,2 分析要爬取的目标 3,保存数据

   1 首先分析页面

开始爬取

创建爬虫项目

scrapy startproject daili

创建爬虫

cd daili

scrapy genspider dd proxy360.cn

创建了一个名叫dd的爬虫

在 items.py 下设置需要爬取的内容

这里爬取ipimport scrapyclass DailiItem(scrapy.Item):    # define the fields for your item here like:    # name = scrapy.Field()    ip =scrapy.Field()    pass然后进入爬虫目录在spiders下的 dd.py
# -*- coding: utf-8 -*-import scrapyfrom daili.items import DailiItem  #导入item.py定义的类名class DdSpider(scrapy.Spider):    name = "dd"    allowed_domains = ["www.proxy360.cn"]
    nations = ['Brazil','Chain','Japan','Vietanm'] #定义好要爬取的名字的后缀    start_urls = []    for nation in nations:  使用for 循环依次加载上        start_urls.append('http://www.proxy360.cn/Region/'+nation  )    def parse(self, response):    #找到要爬取div        sc = response.xpath('//div[@class="proxylistitem"]')        for sub in sc:              开始依次爬取            item = DailiItem()     #调用item定义的类名            item["ip"]= sub.xpath('.//span[1]/text()').extract()[0]            yield item            爬取的内容返回到pipelines。py里配置  setting.py
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
ITEM_PIPELINES = {    'daili.pipelines.DailiPipeline': 300,}进入到pipelines.py
import pyMySQL   # 使用pymysql 连接 如果没有  使用pip install pymysql 下载class DailiPipeline(object):    def __init__(self):        self.conn = pymysql.connect(host="127.0.0.1",user ="root",passWord= "root",db="get")       连接数据库  host 连接地址 user 账号  password密码     def process_item(self, item, spider):        try:            title = item["ip"] #获取 从dd。py传递过来的 内容            sql ="insert into daili(ip) VALUES ('"+title+"')"  传到数据库            print sql            self.conn.query(sql)            return item        except Exception as e:            pass        def close_spider(self):            self.conn.close()  关闭数据库连接


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表