scrapy - 获取最终重定向的 URL

van*_*eto 5 python scrapy

我试图在scrapy中获取最终重定向的URL。例如,如果锚标记具有特定格式:

<a href="http://www.example.com/index.php" class="FOO_X_Y_Z" />
Run Code Online (Sandbox Code Playgroud)

然后我需要获取 URL 重定向到的 URL(如果是,如果是 200,则可以)。例如,我得到适当的锚标签,如下所示:

def parse (self, response)  
    hxs     = HtmlXPathSelector (response);
    anchors = hxs.select("//a[@class='FOO_X_Y_Z']/@href");

    // Lets assume anchor contains the actual link (http://...)
    for anchor in anchors:
        final_url = get_final_url (anchor);   // << I would need something like this

        // Save final_url
Run Code Online (Sandbox Code Playgroud)

因此,如果我访问了http://www.example.com/index.php这将使我通过 10 个重定向,最后它会停止http://www.example.com/final.php- 这就是我需要get_final_url()返回的。

我想通过自己的方式找到解决方案,但我在这里询问是否已经提供了scrapy?

van*_*eto 5

再次假设包含一个实际的 URL,我用urllib2anchor完成了它:

def parse (self, response)  
    hxs     = HtmlXPathSelector (response);
    anchors = hxs.select("//a[@class='FOO_X_Y_Z']/@href");

    // Lets assume anchor contains the actual link (http://...)
    for anchor in anchors:
        final_url = urllib2.open(anchor, None, 1).geturl()

        // Save final_url
Run Code Online (Sandbox Code Playgroud)

urllib2.open()返回带有两个附加方法的类似文件的对象,其中之一是geturl()返回最终 URL(在遵循所有重定向之后)。它不是 Scrapy 的一部分,但它可以工作。

  • 在Python 3中你可以像这样实现它`final_url = urllib.request.urlopen(anchor).geturl()` (2认同)