【问题标题】:Relative URL to absolute URL Scrapy相对 URL 到绝对 URL Scrapy
【发布时间】:2016-03-18 13:38:07
【问题描述】:

我需要帮助在 Scrapy spider 中将相对 URL 转换为绝对 URL。

我需要将起始页上的链接转换为绝对 URL,以获取起始页上潦草项目的图像。我没有成功地尝试了不同的方法来实现这一点,我被困住了。有什么建议吗?

class ExampleSpider(scrapy.Spider):
    name = "example"
    allowed_domains = ["example.com"]
    start_urls = [
        "http://www.example.com/billboard",
        "http://www.example.com/billboard?page=1"
    ]

def parse(self, response):
    image_urls = response.xpath('//div[@class="content"]/section[2]/div[2]/div/div/div/a/article/img/@src').extract()
    relative_url = response.xpath(u'''//div[contains(concat(" ", normalize-space(@class), " "), " content ")]/a/@href''').extract()

    for image_url, url in zip(image_urls, absolute_urls):
        item = ExampleItem()
        item['image_urls'] = image_urls

    request = Request(url, callback=self.parse_dir_contents)
    request.meta['item'] = item
    yield request

【问题讨论】:

  • response.urljoin(relative_url) 可以解决问题,它是 urlparse 中 urljoin 方法的包装,但不导入 urlparse 库。非常方便。

标签: scrapy


【解决方案1】:

主要有以下三种方式来实现:

  1. 使用来自urlliburljoin 函数:

    from urllib.parse import urljoin
    # Same as: from w3lib.url import urljoin
    
    url = urljoin(base_url, relative_url)
    
  2. 使用响应的urljoin 包装方法,如Steve 所述。

    url = response.urljoin(relative_url)
    
  3. 如果您还想从该链接产生一个请求,您可以使用少数响应的follow 方法:

    # It will create a new request using the above "urljoin" method
    yield response.follow(relative_url, callback=self.parse)
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 2011-09-09
    • 2011-01-01
    相关资源
    最近更新 更多