西刺代理爬虫

1. 新建项目和爬虫

scrapy startproject daili_ips
......
cd daili_ips/
#爬虫名称和domains
scrapy genspider xici xicidaili.com

2. 测试

In [1]: import requests
In [2]: r = requests.get('http://www.xicidaili.com/nn/1')
In [3]: r.status_code
Out[3]: 500
In [4]:

返回500, 猜测是没有加User-Agent导致

In [4]: headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}
In [5]:
In [5]: r = requests.get('http://www.xicidaili.com/nn/1', headers=headers)
In [6]: r.status_code
Out[6]: 200
In [7]:

返回正常

3. 在项目的settings中去掉USER_AGENT的注释

# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'

4. 编写items.py

item定义存储哪些字段

import scrapy

class DailiIpsItem(scrapy.Item):
ip = scrapy.Field()
port = scrapy.Field()
position = scrapy.Field()
type = scrapy.Field()
speed = scrapy.Field()
last_check_time = scrapy.Field()

5. 编写spider

# -*- coding: utf-8 -*-
import scrapy
from daili_ips.items import DailiIpsItem class XiciSpider(scrapy.Spider):
name = "xici"
allowed_domains = ["xicidaili.com"]
start_urls = (
'http://www.xicidaili.com/',
) def start_requests(self):
res = []
for i in range(1, 2):
url = 'http://www.xicidaili.com/nn/%d'%i
req = scrapy.Request(url)
# 存储所有对应地址的请求
res.append(req)
return res def parse(self, response):
table = response.xpath('//table[@id="ip_list"]')[0]
trs = table.xpath('//tr')[1:] #去掉标题行
items = []
for tr in trs:
pre_item = DailiIpsItem()
pre_item['ip'] = tr.xpath('td[2]/text()').extract()[0]
pre_item['port'] = tr.xpath('td[3]/text()').extract()[0]
pre_item['position'] = tr.xpath('string(td[4])').extract()[0].strip()
pre_item['type'] = tr.xpath('td[6]/text()').extract()[0]
pre_item['speed'] = tr.xpath('td[7]/div/@title').re('\d+\.\d*')[0]
pre_item['last_check_time'] = tr.xpath('td[10]/text()').extract()[0]
items.append(pre_item)
return items

编写spider的时候可以通过命令行工具scrapy shell url来测试要提取数据的xpath语法, 这样更高效

6. 编写Pipelines

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/top ics/item-pipeline.html
import MySQLdb class DailiIpsPipeline(object):
# 该函数必须返回一个具有数据的dict或者item对象
def process_item(self, item, spider):
DBS = spider.settings.get('DBS')
con = MySQLdb.connect(**DBS)
# 下面这行代码表示设置MySQL使用的字符集为utf8
con.set_character_set('utf8')
cur = con.cursor()
insert_sql = (
"insert into proxy (ip, port, position, type, speed, last_check_time) "
"values (%s,%s,%s,%s,%s,%s);"
)
values = (item['ip'], item['port'], item['position'], item['type'], item['speed'], item['last_check_time'])
# 插入数据库
try:
cur.execute(insert_sql, values)
except Exception, e:
print "插入失败: ", e
con.rollback()
else:
con.commit()
cur.close()
con.close()
return item return item

注意:

这里我刚开始做的时候没有加con.set_character_set('utf8')这一行, 结果报错如下

UnicodeEncodeError: 'latin-1' codec can't encode character

但是我在创建数据表的时候已经设置字符集为utf8, 查资料后是MySQLdb正常情况下会尝试将所有的内容转为latin1字符集处理

所以处理方法就是,设置连接和游标的charset为你所希望的编码

con = MySQLdb.connect(...)
# 设置链接编码
con.set_character_set('utf8')
cur = con.cursor()
# 设置游标编码
cur.execute('SET NAMES utf8;')
cur.execute('SET CHARACTER SET utf8;')
cur.execute('SET CHARACTER_SET_CONNECTION=utf8;')

我在测试后发现仅仅设置连接(con)的编码也不会报错, 所以上述程序并没有设置游标编码

7. 创建MySQL数据表

mysql> create table porxy(
-> id int primary key auto_increment,
-> ip varchar(20),
-> port varchar(20),
-> position varchar(20),
-> type varchar(20),
-> speed varchar(20),
-> last_check_time varchar(20)
-> )charset=utf8;
Query OK, 0 rows affected (0.01 sec) mysql>

8. 启用Pipelines

更改settings.py文件, 取消注释

# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# 'daili_ips.pipelines.SomePipeline': 300,
#}

改为

ITEM_PIPELINES = {
'daili_ips.pipelines.DailiIpsPipeline': 300,
}

后面的数字一般在0-1000以内, 当有多个Pipelines的时候表示执行顺粗, 数字小的先执行

启动爬虫

scrapy crawl xici

Scrapy爬取西刺代理ip流程的更多相关文章

  1. python scrapy 爬取西刺代理ip(一基础篇)(ubuntu环境下) -赖大大

    第一步:环境搭建 1.python2 或 python3 2.用pip安装下载scrapy框架 具体就自行百度了,主要内容不是在这. 第二步:创建scrapy(简单介绍) 1.Creating a p ...

  2. python+scrapy 爬取西刺代理ip(一)

    转自:https://www.cnblogs.com/lyc642983907/p/10739577.html 第一步:环境搭建 1.python2 或 python3 2.用pip安装下载scrap ...

  3. scrapy爬取西刺网站ip

    # scrapy爬取西刺网站ip # -*- coding: utf-8 -*- import scrapy from xici.items import XiciItem class Xicispi ...

  4. 使用XPath爬取西刺代理

    因为在Scrapy的使用过程中,提取页面信息使用XPath比较方便,遂成此文. 在b站上看了介绍XPath的:https://www.bilibili.com/video/av30320885?fro ...

  5. Python四线程爬取西刺代理

    import requests from bs4 import BeautifulSoup import lxml import telnetlib #验证代理的可用性 import pymysql. ...

  6. 手把手教你使用Python爬取西刺代理数据(下篇)

    /1 前言/ 前几天小编发布了手把手教你使用Python爬取西次代理数据(上篇),木有赶上车的小伙伴,可以戳进去看看.今天小编带大家进行网页结构的分析以及网页数据的提取,具体步骤如下. /2 首页分析 ...

  7. python3爬虫-通过requests爬取西刺代理

    import requests from fake_useragent import UserAgent from lxml import etree from urllib.parse import ...

  8. python爬取高匿代理IP(再也不用担心会进小黑屋了)

    为什么要用代理IP 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经做案例的人,却不知道如何去学习更加高深的知识.那么针对这三类人 ...

  9. 爬取西刺ip代理池

    好久没更新博客啦~,今天来更新一篇利用爬虫爬取西刺的代理池的小代码 先说下需求,我们都是用python写一段小代码去爬取自己所需要的信息,这是可取的,但是,有一些网站呢,对我们的网络爬虫做了一些限制, ...

随机推荐

  1. 微信 python 接口 -- itchat 文档

    itchat 一. 安装 $ pip install itchat 特殊的字典使用方式 通过打印 itchat 的用户以及注册消息的参数, 可以发现这些值都是字典. 但实际上 itchat 精心构造了 ...

  2. 【转载】Sublime Text 3065 Keygen and Patcher

    原始日期:2014-10-01 18:25      差不多时隔一年了,Sublime Text 终于更新啦!相信很多友友都已经升级到3065版本了,所以我也特地抽空为大家做了个新版补丁.该补丁仅作为 ...

  3. java执行程序的内存分析系列专栏

    近段时间研究了java的程序执行过程中的内存分配,收获颇多,解决了我最近时间学习java的很多困惑点.写java内存分析系列的目的主要有两个,一来是希望给像我一样的java初学者一定的启发,希望也能解 ...

  4. cURL模拟网页登陆

    <?php /** * Created by PhpStorm. * User: Administrator * Date: 2016/7/13 * Time: 23:15 */ $data=' ...

  5. IP地址分类百科

    IP地址分类介绍 这里讨论IPv4,IP地址分成了A类.B类.C类.C类.E类,如下图所示: 解释: A类以0开头,网络地址有7位,主机地址有24位,举例:A类地址:0 10000000 000000 ...

  6. CSS学习笔记08 浮动

    从CSS学习笔记05 display属性一文中,我们知道div是块元素,会独占一行,即使div的宽度很小,像下面这样 应用display属性的inline属性可以让div与div共享一行,除了这种方法 ...

  7. 【LeetCode】220. Contains Duplicate III

    题目: Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  8. PILLOW图片中加入中文 曲线救国Opencv

    索引 简述 准备 示例 效果图 结语 简述 我在使用opencv2或3的时候想要在图片上添加中文文字,需要去下载Freetype库,编译好链接到opencv库中才能中文的输出.网上大部分在图片中插入中 ...

  9. 用py2exe将python文件转换成exe可执行程序

    1.首先需要安装py2exe模块,下载地址:http://www.lfd.uci.edu/~gohlke/pythonlibs/ 然后用pip install 命令安装py2exe模块,如果你用的py ...

  10. [转]ubuntu搭建LAMP环境

    首先下载安装apache2 输入:sudo apt-get install apache2 安装完毕后,在浏览器中输入:localhost 可以看到apache的默认主页 紧接着安装php5 输入:s ...