手机App抓包爬虫
1. items.py
class DouyuspiderItem(scrapy.Item):
name = scrapy.Field()
imagesUrls = scrapy.Field()
imagesPath = scrapy.Field()
2. spiders/douyu.py
import scrapy
import json
from douyuSpider.items import DouyuspiderItem
class DouyuSpider(scrapy.Spider):
name = "douyu"
allowd_domains = ["http://capi.douyucdn.cn"]
offset = 0
url = "http://capi.douyucdn.cn/api/v1/getVerticalRoom?limit=20&offset="
start_urls = [url + str(offset)]
def parse(self, response):
data = json.loads(response.text)["data"]
for each in data:
item = DouyuspiderItem()
item["name"] = each["nickname"]
item["imagesUrls"] = each["vertical_src"]
yield item
self.offset += 20
yield scrapy.Request(self.url + str(self.offset), callback = self.parse)
3. 设置setting.py
ITEM_PIPELINES = {'douyuSpider.pipelines.ImagesPipeline': 1}
IMAGES_STORE = "/Users/Power/lesson_python/douyuSpider/Images"
USER_AGENT = 'DYZB/2.290 (iPhone; iOS 9.3.4; Scale/2.00)'
4. pipelines.py
import scrapy
import os
from scrapy.pipelines.images import ImagesPipeline
from scrapy.utils.project import get_project_settings
class ImagesPipeline(ImagesPipeline):
IMAGES_STORE = get_project_settings().get("IMAGES_STORE")
def get_media_requests(self, item, info):
image_url = item["imagesUrls"]
yield scrapy.Request(image_url)
def item_completed(self, results, item, info):
image_path = [x["path"] for ok, x in results if ok]
os.rename(self.IMAGES_STORE + "/" + image_path[0], self.IMAGES_STORE + "/" + item["name"] + ".jpg")
item["imagesPath"] = self.IMAGES_STORE + "/" + item["name"]
return item
在项目根目录下新建main.py文件,用于调试
from scrapy import cmdline
cmdline.execute('scrapy crawl douyu'.split())
执行程序
py2 main.py