美文网首页
新建爬虫项目(crawlspider)下载图片

新建爬虫项目(crawlspider)下载图片

作者: 八盖 | 来源:发表于2019-06-29 09:59 被阅读0次

创建项目:
scrapy startproject ang
创建爬虫:
scrapy genspider -t crawl angel angelimg.com

总结:
1:rule规则是从上到下执行的 所以需要倒着写

  rules = (
        # 图集翻页  需要翻页 提取图片url  供下载用
        Rule(LinkExtractor(allow=r'http://www.angelimg.com/ang/\d+/\d+'), callback='parse_item',           follow=True),
        # 图集首页 不要回调
        Rule(LinkExtractor(allow=r'http://www.angelimg.com/ang/\d+'), follow=True),
        # 首页翻页,不需要回调
        Rule(LinkExtractor(allow=r'http://www.angelimg.com/index/\d+'), follow=True),
    )

2:图片有防跨域请求的 所以需要在settings里面找到默认请求头 在里面加上referer(参考页):"域名" 指定来源:

DEFAULT_REQUEST_HEADERS = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en',
    'Referer': 'http://www.angelimg.com'
}

3:需要在settings里面添加代理IP池 在中间件里面的process_request函数下面调用 还要写一个初始化函数

def __init__(self, settings):
    self.settings = settings
    self.ips = settings.getlist("IPS")

def process_request(self, request, spider):
    if "proxy" not in request.meta:
        proxy = random.choice(self.ips)
        print(proxy, "---------------------------------")
        request.meta['proxy'] = proxy
    return None

相关文章

网友评论

      本文标题:新建爬虫项目(crawlspider)下载图片

      本文链接:https://www.haomeiwen.com/subject/zhmucctx.html