Scrapy框架爬取西刺代理网免费高匿代理的实现代码

yipeiwu_com6年前Python爬虫

分析

需求:

爬取西刺代理网免费高匿代理,并保存到MySQL数据库中。

这里只爬取前10页中的数据。

思路:

  1. 分析网页结构,确定数据提取规则
  2. 创建Scrapy项目
  3. 编写item,定义数据字段
  4. 编写spider,实现数据抓取
  5. 编写Pipeline,保存数据到数据库中
  6. 配置settings.py文件
  7. 运行爬虫项目

代码实现

items.py

import scrapy
class XicidailiItem(scrapy.Item):
  # 国家
  country=scrapy.Field()
  # IP地址
  ip=scrapy.Field()
  # 端口号
  port=scrapy.Field()
  # 服务器地址
  address=scrapy.Field()
  # 是否匿名
  anonymous=scrapy.Field()
  # 类型
  type=scrapy.Field()
  # 速度
  speed=scrapy.Field()
  # 连接时间
  connect_time=scrapy.Field()
  # 存活时间
  alive_time=scrapy.Field()
  # 验证时间
  verify_time=scrapy.Field()

xicidaili_spider.py

# !/usr/bin/env python
# -*- coding:utf-8 -*-
import scrapy
from myscrapy.items import XicidailiItem
class XicidailiSpider(scrapy.Spider):
  name = 'xicidaili'
  allowed_domains=['www.xicidaili.com']
  # start_urls=['http://www.xicidaili.com/nn/1']
  def start_requests(self):
    urls=[]
    for i in range(1,11):
      urls.append('http://www.xicidaili.com/nn/'+str(i))
    for url in urls:
      yield scrapy.Request(url,callback=self.parse,method='GET')
  def parse(self, response):
    tr_list=response.xpath('//table[@id="ip_list"]/tr')
    for tr in tr_list[1:]: # 过滤掉表头行
      item=XicidailiItem()
      item['country']=tr.xpath('./td[1]/img/@alt').extract_first()
      item['ip']=tr.xpath('./td[2]/text()').extract_first()
      item['port']=tr.xpath('./td[3]/text()').extract_first()
      item['address']=tr.xpath('./td[4]/a/text()').extract_first()
      item['anonymous']=tr.xpath('./td[5]/text()').extract_first()
      item['type']=tr.xpath('./td[6]/text()').extract_first()
      item['speed']=tr.xpath('./td[7]/div/@title').re(r'\d{1,3}\.\d{0,}')[0]
      item['connect_time']=tr.xpath('./td[8]/div/@title').re(r'\d{1,3}\.\d{0,}')[0]
      item['alive_time']=tr.xpath('./td[9]/text()').extract_first()
      item['verify_time']=tr.xpath('./td[10]/text()').extract_first()
      yield item

pipelines.py

class XicidailiPipeline(object):
  """
  西刺代理爬虫 item Pipeline
  create table xicidaili(
    id int primary key auto_increment,
    country varchar(10) not null,
    ip varchar(30) not null,
    port varchar(10) not null,
    address varchar(30) not null,
    anonymous varchar(10) not null,
    type varchar(20) not null,
    speed varchar(10) not null,
    connect_time varchar(20) not null,
    alive_time varchar(20) not null,
    verify_time varchar(20) not null);
  """
  def __init__(self):
    self.connection = pymysql.connect(host='localhost',
                     user='root',
                     password='123456',
                     db='mydb',
                     charset='utf8', # 不能用utf-8
                     cursorclass=pymysql.cursors.DictCursor)
  def process_item(self,item,spider):
    with self.connection.cursor() as cursor:
      sql='insert into xicidaili' \
        '(country,ip,port,address,anonymous,type,speed,connect_time,alive_time,verify_time) values' \
        '(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);'
      args=(item['country'],item['ip'],item['port'],item['address'],item['anonymous'],item['type'],item['speed'],item['connect_time'],item['alive_time'],item['verify_time'])
      spider.logger.info(args)
      cursor.execute(sql,args)
    self.connection.commit()
  def close_spider(self,spider):
    self.connection.close()

settings.py

ITEM_PIPELINES = {
  'myscrapy.pipelines.XicidailiPipeline': 300,
}

结果

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

Python实现抓取城市的PM2.5浓度和排名

Python实现抓取城市的PM2.5浓度和排名

主机环境:(Python2.7.9 / Win8_64 / bs4) 利用BeautifulSoup4来抓取 www.pm25.com 上的PM2.5数据,之所以抓取这个网站,是因为上面...

爬虫代理池Python3WebSpider源代码测试过程解析

这篇文章主要介绍了爬虫代理池Python3WebSpider源代码测试过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 元类属性...

解决Python网页爬虫之中文乱码问题

解决Python网页爬虫之中文乱码问题

Python是个好工具,但是也有其固有的一些缺点。最近在学习网页爬虫时就遇到了这样一种问题,中文网站爬取下来的内容往往中文显示乱码。看过我之前博客的同学可能知道,之前爬取的一个学校网页就...

Python爬虫爬取美剧网站的实现代码

Python爬虫爬取美剧网站的实现代码

一直有爱看美剧的习惯,一方面锻炼一下英语听力,一方面打发一下时间。之前是能在视频网站上面在线看的,可是自从广电总局的限制令之后,进口的美剧英剧等貌似就不在像以前一样同步更新了。但是,作为...

利用Python爬取可用的代理IP

利用Python爬取可用的代理IP

前言 就以最近发现的一个免费代理IP网站为例:http://www.xicidaili.com/nn/。在使用的时候发现很多IP都用不了。 所以用Python写了个脚本,该脚本可以把能用...