Scrapy爬取西刺代理ip流程
西刺代理爬虫
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流程的更多相关文章
- python scrapy 爬取西刺代理ip(一基础篇)(ubuntu环境下) -赖大大
第一步:环境搭建 1.python2 或 python3 2.用pip安装下载scrapy框架 具体就自行百度了,主要内容不是在这. 第二步:创建scrapy(简单介绍) 1.Creating a p ...
- python+scrapy 爬取西刺代理ip(一)
转自:https://www.cnblogs.com/lyc642983907/p/10739577.html 第一步:环境搭建 1.python2 或 python3 2.用pip安装下载scrap ...
- scrapy爬取西刺网站ip
# scrapy爬取西刺网站ip # -*- coding: utf-8 -*- import scrapy from xici.items import XiciItem class Xicispi ...
- 使用XPath爬取西刺代理
因为在Scrapy的使用过程中,提取页面信息使用XPath比较方便,遂成此文. 在b站上看了介绍XPath的:https://www.bilibili.com/video/av30320885?fro ...
- Python四线程爬取西刺代理
import requests from bs4 import BeautifulSoup import lxml import telnetlib #验证代理的可用性 import pymysql. ...
- 手把手教你使用Python爬取西刺代理数据(下篇)
/1 前言/ 前几天小编发布了手把手教你使用Python爬取西次代理数据(上篇),木有赶上车的小伙伴,可以戳进去看看.今天小编带大家进行网页结构的分析以及网页数据的提取,具体步骤如下. /2 首页分析 ...
- python3爬虫-通过requests爬取西刺代理
import requests from fake_useragent import UserAgent from lxml import etree from urllib.parse import ...
- python爬取高匿代理IP(再也不用担心会进小黑屋了)
为什么要用代理IP 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经做案例的人,却不知道如何去学习更加高深的知识.那么针对这三类人 ...
- 爬取西刺ip代理池
好久没更新博客啦~,今天来更新一篇利用爬虫爬取西刺的代理池的小代码 先说下需求,我们都是用python写一段小代码去爬取自己所需要的信息,这是可取的,但是,有一些网站呢,对我们的网络爬虫做了一些限制, ...
随机推荐
- WCF入门, 到创建一个简单的WCF应用程序
什么是WCF? WCF, 英文全称(windows Communication Foundation) , 即为windows通讯平台. windows想到这里大家都知道了 , WCF也正是由微软公 ...
- 深入浅出HTTP协议
超文本传输协议(HTTP,HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议.所有的WWW文件都必须遵守这个标准.设计HTTP最初的目的是为了提供一种发布和接 ...
- jsp图片上传
1.要实现图片上传,首先需要一个组件,这里我用的是smartupload.jar可以到这里下载http://download.csdn.net/detail/mengdecike/8279247 2. ...
- 2~62位任意进制转换(c++)
进制转换的符号表为[0-9a-zA-Z],共61个字符,最大可表示62进制. 思路是原进制先转换为10进制,再转换到目标进制. 疑问: 对于负数,有小伙伴说可以直接将符号丢弃,按照整数进行进位转换,最 ...
- Swift三元条件运算
三元条件运算的特殊在于它是有三个操作数的运算符,它的原型是问题?答案1:答案2.它简洁地表达根据问题成立与否作出二选一的操作.如果问题成立,返回答案1的结果; 如果不成立,返回答案2的结果. 使用三元 ...
- bootstrap图标字体不出来问题的解决办法
@font-face { font-family: 'Glyphicons Halflings'; src: url('/Scripts/bootstrap/fonts/glyphicons-half ...
- App Extensions篇之Share Extension
转载请注明出处:http://www.cnblogs.com/zhanggui/p/7119572.html 1.前言 这里主要是对App Extension的一些介绍以及详细给大家介绍一下Share ...
- Unity3D-游戏中的技能碰撞检测
在游戏战斗中,我们会用到各种各样的碰撞检测,来判断是否打中了目标 比如扇形检测/圆形检测 还有矩形检测,王者荣耀里后羿的大招就是一个很长的矩形碰撞体 这些在Unity3D引擎中其实都封装好了一些Col ...
- CSS 回流(reflow)
摘录: 1. 回流 回流是指浏览器为了重新渲染部分或者全部的文档而重新计算文档中元素的位置和几何构造的过程. 因为回流可能导致整个dom树的重新构造,所以会影响性能. 2. display:no ...
- JavaScript一个猜数字游戏
效果图: 代码: <body> <script type="text/javascript"> window.onload = newgame; //页面载 ...