最近睡了午覺之后涣仿,感覺一點(diǎn)精神都沒有凰兑,我覺得需要刺激一下款青。
爬取的網(wǎng)站長(zhǎng)這個(gè)樣子:
運(yùn)行
默認(rèn)16個(gè)并發(fā),我放公司不知道跑了多久贸伐,周末公司停電了勘天,不知道這個(gè)網(wǎng)站有沒有反爬蟲,我現(xiàn)在還沒遇到捉邢。
有代理脯丝,代理都是各大代理網(wǎng)站的免費(fèi)代理:
沒有代理:
有代理就像蝸牛一樣,代理失敗率還高的嚇人伏伐,免費(fèi)的代理就是不靠譜宠进。
結(jié)果
pycharm 如何使用anaconda里面的環(huán)境
File->Default settings->Default project->project interpreter
接著點(diǎn)擊 project interpreter 的右邊的小齒輪,選擇 add local 藐翎,選擇anaconda文件路徑下的python.exe材蹬。接著pycharm會(huì)更新解釋器荆隘,導(dǎo)入模塊等袖订,要稍等一點(diǎn)時(shí)間。
安裝scrapy
pip install scrapy
windos安裝這個(gè)會(huì)出錯(cuò)歇万,因?yàn)橛袃蓚€(gè)依賴模塊twisted pywin32安裝不上末贾,所以只有進(jìn)行本地安裝闸溃。
到這個(gè)網(wǎng)站--https://www.lfd.uci.edu/~gohlke/pythonlibs/下載對(duì)應(yīng)的版本安裝,然后在使用上面的那個(gè)命令拱撵。Linux類的電腦辉川,不會(huì)出現(xiàn)這個(gè)問題的。
本地安裝命令,例如安裝Twisted
pin install Twisted?17.9.0?cp36?cp36m?win_amd64.whl
還有安裝一個(gè)pillow,用來處理圖片裕膀。
pip install pillow
運(yùn)行scrapy可能出現(xiàn)問題员串,應(yīng)該是pywin32出錯(cuò),出錯(cuò)的原因就是沒有加入環(huán)境變量昼扛。可以把pywin32_system32里面的文件放到系統(tǒng)中的system32 或者虛擬環(huán)境中的scripts中欲诺。
新建項(xiàng)目
我們先來看下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命令來創(chuàng)建項(xiàng)目:
scrapy startproject gallery
用pycharm打開項(xiàng)目抄谐,開始coding,代碼來襲
##### 爬取規(guī)則(Spider)
#gallery_spider.py
import scrapy
from scrapy import Request
from gallery.items import GalleryItem
class GallerySpider(scrapy.Spider):
# Spider 的唯一標(biāo)識(shí) 扰法,必不可少
name = "gallery_spider"
# 爬取開始連接 是一個(gè)列表
start_urls = ['http://www.55156.com/weimeiyijing/fengjingtupian']
# 默認(rèn)的解析方法
def parse(self, response):
# 取當(dāng)前頁(yè)所有的圖片索引url
urls = response.xpath('//ul[@class="liL"]/li/a/@href').extract()
self.logger.info('當(dāng)前父圖片urls----->{}'.format(urls))
for url in urls:
# 丟給調(diào)度器 加入請(qǐng)求隊(duì)列
yield Request(url=url, callback=self.img_parse)
# yield Request(url='http://www.55156.com/weimeiyijing/fengjingtupian/146515.html', callback=self.img_parse)
# 下一頁(yè)的url
next_page = response.css('.pages ul li ::attr(href)')[-2].extract()
# 判斷是否存在下一頁(yè) 和 不最后一頁(yè)
if next_page and not next_page == '#':
self.logger.info('存在列表下一頁(yè)------>{}'.format(next_page))
yield Request(url=response.urljoin(next_page), callback=self.parse)
def img_parse(self, respose):
'''
詳細(xì)圖片頁(yè)的解析
'''
# 定義提取數(shù)據(jù)結(jié)構(gòu)
item = GalleryItem()
#取圖片url
img_url = respose.css('.articleBody p a img ::attr(src)').extract_first()
# 取圖片的標(biāo)題
img_dir = respose.css('.articleTitle h1 ::text').extract_first()
# 賦值給item
item['image_url'] = img_url
item['image_dir'] = img_dir
# 取所有頁(yè)數(shù)
next_page = respose.css('.pages ul li a ::attr(href)').extract()
# 判斷頁(yè)數(shù)不為空
if next_page:
#取下一頁(yè)url
next_page = next_page[-1]
# 判斷是否存在下一頁(yè) 和 不最后一頁(yè) 實(shí)際上這個(gè)地方不用判斷是否存在 因?yàn)樵谥耙呀?jīng)做了一次判斷
if next_page and not next_page == '#':
self.logger.info('開始爬取圖片下一頁(yè)-------->{}'.format(next_page))
# 丟給調(diào)度器 加入請(qǐng)求隊(duì)列
yield Request(url=respose.urljoin(next_page), callback=self.img_parse)
yield item
items
#items.py
import scrapy
class GalleryItem(scrapy.Item):
'''
定義提取數(shù)據(jù)的結(jié)構(gòu)
'''
image_url= scrapy.Field()
image_dir= scrapy.Field()
中間件
#middlewares.py
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware
import random
class GallerySpiderMiddleware(UserAgentMiddleware):
'''
設(shè)置請(qǐng)求頭 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):
'''
請(qǐng)求之前的回調(diào)
'''
# 隨機(jī)取一個(gè)user-agent
ua = random.choice(self.user_agent_list)
spider.logger.info("當(dāng)前UA----->" + ua)
# 給請(qǐng)求頭設(shè)置User-Agent
request.headers.setdefault('User-Agent', ua)
user-agent這個(gè)網(wǎng)上一大堆蛹含。http://www.reibang.com/p/da6a44d0791e
管道
#pipelines.py
import os
import scrapy
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline
class GalleryPipeline(ImagesPipeline):
'''
用來圖片的存儲(chǔ)
'''
def get_media_requests(self, item, info):
'''
圖片請(qǐng)求
'''
yield scrapy.Request(item['image_url'], meta={'item': item})
def item_completed(self, results, item, info):
'''
下載后的回調(diào)
'''
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):
'''
圖片路徑設(shè)置
'''
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規(guī)則
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: 默認(rèn)請(qǐng)求頭
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,
}
運(yùn)行入口
#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()
運(yùn)行可能出現(xiàn)錯(cuò)誤(windos)
ImportError: No module named win32api
安裝pywin32模塊
pip install pywin32
源代碼
這個(gè)實(shí)際比較簡(jiǎn)單的,我就不貼代碼了塞颁,我就寫了高清套圖那個(gè)模塊浦箱。
github地址
似乎上班有點(diǎn)精神了吸耿。。酷窥。