检查网址是否有404错误scrapy

时间:2013-04-07 17:43:06

标签: python web-scraping http-status-code-404 scrapy

我正在浏览一组页面并且我不确定它们有多少,但是当前页面由url中存在的简单数字表示(例如“http://www.website.com/page/1”)

我想在scrapy中使用for循环来增加页面的当前猜测并在达到404时停止。我知道从请求返回的响应包含此信息,但我不知道如何自动从请求中获取响应。

关于如何做到这一点的任何想法?

目前我的代码类似于:

def start_requests(self):
    baseUrl = "http://website.com/page/"
    currentPage = 0
    stillExists = True
    while(stillExists):
        currentUrl = baseUrl + str(currentPage)
        test = Request(currentUrl)
        if test.response.status != 404: #This is what I'm not sure of
            yield test
            currentPage += 1
        else:
            stillExists = False

2 个答案:

答案 0 :(得分:2)

您需要产生/返回请求以检查状态,创建Request对象实际上并不发送它。

class MySpider(BaseSpider):
    name = 'website.com'
    baseUrl = "http://website.com/page/"

    def start_requests(self):
        yield Request(self.baseUrl + '0')

    def parse(self, response):
        if response.status != 404:
            page = response.meta.get('page', 0) + 1
            return Request('%s%s' % (self.baseUrl, page), meta=dict(page=page))

答案 1 :(得分:1)

您可以这样做:

from __future__ import print_function
import urllib2

baseURL = "http://www.website.com/page/"

for n in xrange(100):
    fullURL = baseURL + str(n)
    #print fullURL
    try:
        req = urllib2.Request(fullURL)
        resp = urllib2.urlopen(req)
        if resp.getcode() == 404:
            #Do whatever you want if 404 is found
            print ("404 Found!")
        else:
            #Do your normal stuff here if page is found.
            print ("URL: {0} Response: {1}".format(fullURL, resp.getcode()))
    except:
        print ("Could not connect to URL: {0} ".format(fullURL))

这会遍历范围并尝试通过urllib2连接到每个网址。我不知道scapy或您的示例函数如何打开网址,但这是一个如何通过urllib2执行此操作的示例。

请注意,大多数使用此类网址格式的网站通常都会运行CMS,该网站可以自动将不存在的网页重定向到自定义404 - Not Found页面,该页面仍会显示为HTTP状态代码200.这种情况下,查找可能显示的页面的最佳方式实际上只是自定义404页面,您应该进行一些屏幕抓取并查找在“正常”页面返回期间可能不会出现的任何内容,例如文本“找不到页面”或类似且独特的自定义404页面。