【问题标题】:Checking a url for a 404 error scrapy检查 404 错误的 url
【发布时间】:2013-03-29 17:43:44
【问题描述】:

我正在浏览一组页面,我不确定有多少,但当前页面由 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

【问题讨论】:

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


    【解决方案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 连接到每个 URL。我不知道 scapy 或您的示例函数如何打开 URL,但这是一个如何通过 urllib2 进行操作的示例。

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

    【讨论】:

    • 根据我的经验,大多数自定义 404 页面都会返回 404 状态码。
    • 原来他们的没有,如果不检查他们的内容,我就无法真正解决这个问题,这使得它太慢了,但这个答案本来可以正常解决问题的。
    【解决方案2】:

    您需要yield/return请求以检查状态,创建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))
    

    【讨论】:

      猜你喜欢
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 2011-04-05
      • 2013-12-08
      • 2013-05-23
      • 2016-12-12
      • 2021-11-13
      相关资源
      最近更新 更多