简体   繁体   English

抓紧所有链接并获取状态

[英]Scrapy follow all the links and get status

I want to follow all the links of the website and get the status of every links like 404,200. 我想关注网站的所有链接,并获取每个链接的状态,例如404,200。 I tried this: 我尝试了这个:

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor

class someSpider(CrawlSpider):
  name = 'linkscrawl'
  item = []
  allowed_domains = ['mysite.com']
  start_urls = ['//mysite.com/']

  rules = (Rule (LinkExtractor(), callback="parse_obj", follow=True),
  )

  def parse_obj(self,response):
    item = response.url
    print(item)

I can see the links without status code on the console like: 我可以在控制台上看到没有状态代码的链接,例如:

mysite.com/navbar.html
mysite.com/home
mysite.com/aboutus.html
mysite.com/services1.html
mysite.com/services3.html
mysite.com/services5.html

but how to save in text file with status of all links? 但是如何保存所有链接状态的文本文件?

I solved this as below. 我如下解决了这个问题。 Hope this will help for anyone who needs. 希望这对任何需要的人有帮助。

import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor

class LinkscrawlItem(scrapy.Item):
    # define the fields for your item here like:
    link = scrapy.Field()
    attr = scrapy.Field()

class someSpider(CrawlSpider):
  name = 'linkscrawl'
  item = []

  allowed_domains = ['mysite.com']
  start_urls = ['//www.mysite.com/']

  rules = (Rule (LinkExtractor(), callback="parse_obj", follow=True),
  )

  def parse_obj(self,response):
    #print(response.status)
    item = LinkscrawlItem()
    item["link"] = str(response.url)+":"+str(response.status)
    # item["link_res"] = response.status
    # status = response.url
    # item = response.url
    # print(item)
    filename = 'links.txt'
    with open(filename, 'a') as f:
      f.write('\n'+str(response.url)+":"+str(response.status)+'\n')
    self.log('Saved file %s' % filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM