Python爬虫(Scrapy)爬取秀人网
最近睡了午觉之后,感觉一点精神都没有,我觉得需要刺激一下。
爬取的网站长这个样子:
爬取的网站.png运行
默认16个并发,我放公司不知道跑了多久,周末公司停电了,不知道这个网站有没有反爬虫,我现在还没遇到。
有代理,代理都是各大代理网站的免费代理:
proxy.gif没有代理:
noproxy.gif有代理就像蜗牛一样,代理失败率还高的吓人,免费的代理就是不靠谱。
结果
大小.png 目录.png 结果.pngpycharm 如何使用anaconda里面的环境
File->Default settings->Default project->project interpreter
接着点击 project interpreter 的右边的小齿轮,选择 add local ,选择anaconda文件路径下的python.exe。接着pycharm会更新解释器,导入模块等,要稍等一点时间。
gif.gif安装scrapy
pip install scrapy
windos安装这个会出错,因为有两个依赖模块twisted pywin32安装不上,所以只有进行本地安装。
到这个网站--https://www.lfd.uci.edu/~gohlke/pythonlibs/下载对应的版本安装,然后在使用上面的那个命令。Linux类的电脑,不会出现这个问题的。
本地安装命令,例如安装Twisted
pin install Twisted‑17.9.0‑cp36‑cp36m‑win_amd64.whl
还有安装一个pillow,用来处理图片。
pip install pillow
运行scrapy可能出现问题,应该是pywin32出错,出错的原因就是没有加入环境变量。可以把pywin32_system32里面的文件放到系统中的system32 或者虚拟环境中的scripts中。
新建项目
我们先来看下scrapy中的命令:
Scrapy 1.4.0 - no active project
Usage:
scrapy <command> [options] [args]
Available commands:
bench Run quick benchmark test
fetch Fetch a URL using the Scrapy downloader
genspider Generate new spider using pre-defined templates
runspider Run a self-contained spider (without creating a project)
settings Get settings values
shell Interactive scraping console
startproject Create new project
version Print Scrapy version
view Open URL in browser, as seen by Scrapy
[ more ] More commands available when run from project directory
Use "scrapy <command> -h" to see more info about a command
用scrapy命令来创建项目:
scrapy startproject gallery
用pycharm打开项目,开始coding,代码来袭
##### 爬取规则(Spider)
#gallery_spider.py
import scrapy
from scrapy import Request
from gallery.items import GalleryItem
class GallerySpider(scrapy.Spider):
# Spider 的唯一标识 ,必不可少
name = "gallery_spider"
# 爬取开始连接 是一个列表
start_urls = ['http://www.55156.com/weimeiyijing/fengjingtupian']
# 默认的解析方法
def parse(self, response):
# 取当前页所有的图片索引url
urls = response.xpath('//ul[@class="liL"]/li/a/@href').extract()
self.logger.info('当前父图片urls----->{}'.format(urls))
for url in urls:
# 丢给调度器 加入请求队列
yield Request(url=url, callback=self.img_parse)
# yield Request(url='http://www.55156.com/weimeiyijing/fengjingtupian/146515.html', callback=self.img_parse)
# 下一页的url
next_page = response.css('.pages ul li ::attr(href)')[-2].extract()
# 判断是否存在下一页 和 不最后一页
if next_page and not next_page == '#':
self.logger.info('存在列表下一页------>{}'.format(next_page))
yield Request(url=response.urljoin(next_page), callback=self.parse)
def img_parse(self, respose):
'''
详细图片页的解析
'''
# 定义提取数据结构
item = GalleryItem()
#取图片url
img_url = respose.css('.articleBody p a img ::attr(src)').extract_first()
# 取图片的标题
img_dir = respose.css('.articleTitle h1 ::text').extract_first()
# 赋值给item
item['image_url'] = img_url
item['image_dir'] = img_dir
# 取所有页数
next_page = respose.css('.pages ul li a ::attr(href)').extract()
# 判断页数不为空
if next_page:
#取下一页url
next_page = next_page[-1]
# 判断是否存在下一页 和 不最后一页 实际上这个地方不用判断是否存在 因为在之前已经做了一次判断
if next_page and not next_page == '#':
self.logger.info('开始爬取图片下一页-------->{}'.format(next_page))
# 丢给调度器 加入请求队列
yield Request(url=respose.urljoin(next_page), callback=self.img_parse)
yield item
items
#items.py
import scrapy
class GalleryItem(scrapy.Item):
'''
定义提取数据的结构
'''
image_url= scrapy.Field()
image_dir= scrapy.Field()
中间件
#middlewares.py
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware
import random
class GallerySpiderMiddleware(UserAgentMiddleware):
'''
设置请求头 User-Agent
'''
user_agent_list = [
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
"Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
"Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
"Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
"Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
"Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
"Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
"Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10"
]
def process_request(self, request, spider):
'''
请求之前的回调
'''
# 随机取一个user-agent
ua = random.choice(self.user_agent_list)
spider.logger.info("当前UA----->" + ua)
# 给请求头设置User-Agent
request.headers.setdefault('User-Agent', ua)
user-agent这个网上一大堆。http://www.jianshu.com/p/da6a44d0791e
管道
#pipelines.py
import os
import scrapy
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline
class GalleryPipeline(ImagesPipeline):
'''
用来图片的存储
'''
def get_media_requests(self, item, info):
'''
图片请求
'''
yield scrapy.Request(item['image_url'], meta={'item': item})
def item_completed(self, results, item, info):
'''
下载后的回调
'''
image_paths = [x['path'] for ok,x in results if ok]
# for ok, x in results:
# if ok:
# print(x['path'])
if not image_paths:
print('{}/{}------文件保存失败'.format(item['image_dir'], item['image_url']))
raise DropItem("Item contains no images")
else:
print('{}/{}------文件保存成功'.format(item['image_dir'], item['image_url']))
return item
def file_path(self, request, response=None, info=None):
'''
图片路径设置
'''
item = request.meta['item']
img_name = os.path.basename(item['image_url'])
index = item['image_dir'].find('(')
if index == -1:
index = item['image_dir'].find('(')
if not index == -1:
item['image_dir'] = item['image_dir'][:index]
filename = u'{}/{}'.format(item['image_dir'], img_name)
return filename
配置文件
#settings.py
BOT_NAME = 'gallery'
SPIDER_MODULES = ['gallery.spiders']
NEWSPIDER_MODULE = 'gallery.spiders'
# Obey robots.txt rules 是否遵守robots规则
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
#DOWNLOAD_DELAY = 3
# Disable cookies (enabled by default) cookeie是否禁用
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers: 默认请求头
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding:': 'gzip, deflate',
'Accept-Language': 'en_US,en;q=0.8',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded'
}
# Enable or disable downloader middlewares 下载中间件
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
'gallery.middlewares.GallerySpiderMiddleware': 543,
}
# 文件保存的地址
IMAGES_STORE = 'F:\\gallery'
# 管道
ITEM_PIPELINES = {
'gallery.pipelines.GalleryPipeline': 300,
}
运行入口
#run.py
from scrapy.cmdline import execute
import os, sys
def func():
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
execute('scrapy crawl gallery_spider'.split(' '))
if __name__ == '__main__':
func()
源代码
这个实际比较简单的,我就不贴代码了,我就写了高清套图那个模块。
github地址
似乎上班有点精神了。。。