Python Scrapy:将相对路径转换为绝对路径

2024-06-25

我根据下面的伟大人士提供的解决方案修改了代码;我收到代码下方显示的错误。

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from dmoz2.items import DmozItem

class DmozSpider(BaseSpider):
   name = "namastecopy2"
   allowed_domains = ["namastefoods.com"]
   start_urls = [
    "http://www.namastefoods.com/products/cgi-bin/products.cgi?Function=show&Category_Id=4&Id=1",
    "http://www.namastefoods.com/products/cgi-bin/products.cgi?Function=show&Category_Id=4&Id=12",    

]

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    sites = hxs.select('/html/body/div/div[2]/table/tr/td[2]/table/tr')
    items = []
    for site in sites:
        item = DmozItem()
        item['manufacturer'] = 'Namaste Foods'
        item['productname'] = site.select('td/h1/text()').extract()
        item['description'] = site.select('//*[@id="info-col"]/p[7]/strong/text()').extract()
        item['ingredients'] = site.select('td[1]/table/tr/td[2]/text()').extract()
        item['ninfo'] = site.select('td[2]/ul/li[3]/img/@src').extract()
        #insert code that will save the above image path for ninfo as an absolute path
        base_url = get_base_url(response)
        relative_url = site.select('//*[@id="showImage"]/@src').extract()
        item['image_urls'] = urljoin_rfc(base_url, relative_url)
        items.append(item)
    return items

我的 items.py 看起来像这样:

from scrapy.item import Item, Field

class DmozItem(Item):
    # define the fields for your item here like:
    productid = Field()
    manufacturer = Field()
    productname = Field()
    description = Field()
    ingredients = Field()
    ninfo = Field()
    imagename = Field()
    image_paths = Field()
    relative_images = Field()
    image_urls = Field()
    pass

我需要蜘蛛为 items['relative_images'] 获取的相对路径转换为绝对路径并保存在 items['image_urls'] 中,以便我可以从该蜘蛛本身下载图像。例如,蜘蛛获取的relative_images路径是“../../files/images/small/8270-BrowniesHiResClip.jpg”,应将其转换为“http://namastefoods.com/files/images/small” /8270-BrowniesHiResClip.jpg', & 存储在 items['image_urls'] 中

我还需要将 items['ninfo'] 路径存储为绝对路径。

运行上述代码时出错:

2011-06-28 17:18:11-0400 [scrapy] INFO: Scrapy 0.12.0.2541 started (bot: dmoz2)
2011-06-28 17:18:11-0400 [scrapy] DEBUG: Enabled extensions: TelnetConsole, SpiderContext, WebService, CoreStats, CloseSpider
2011-06-28 17:18:11-0400 [scrapy] DEBUG: Enabled scheduler middlewares: DuplicatesFilterMiddleware
2011-06-28 17:18:11-0400 [scrapy] DEBUG: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, RedirectMiddleware, CookiesMiddleware, HttpCompressionMiddleware, DownloaderStats
2011-06-28 17:18:11-0400 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2011-06-28 17:18:11-0400 [scrapy] DEBUG: Enabled item pipelines: MyImagesPipeline
2011-06-28 17:18:11-0400 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:6023
2011-06-28 17:18:11-0400 [scrapy] DEBUG: Web service listening on 0.0.0.0:6080
2011-06-28 17:18:11-0400 [namastecopy2] INFO: Spider opened
2011-06-28 17:18:12-0400 [namastecopy2] DEBUG: Crawled (200) <GET http://www.namastefoods.com/products/cgi-bin/products.cgi?Function=show&Category_Id=4&Id=12> (referer: None)
2011-06-28 17:18:12-0400 [namastecopy2] ERROR: Spider error processing <http://www.namastefoods.com/products/cgi-bin/products.cgi?Function=show&Category_Id=4&Id=12> (referer: <None>)
    Traceback (most recent call last):
      File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/internet/base.py", line 1137, in mainLoop
        self.runUntilCurrent()
      File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/internet/base.py", line 757, in runUntilCurrent
        call.func(*call.args, **call.kw)
      File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/internet/defer.py", line 243, in callback
        self._startRunCallbacks(result)
      File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/internet/defer.py", line 312, in _startRunCallbacks
        self._runCallbacks()
    --- <exception caught here> ---
      File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/internet/defer.py", line 328, in _runCallbacks
        self.result = callback(self.result, *args, **kw)
      File "/***/***/***/***/***/***/spiders/namaste_copy2.py", line 30, in parse
        item['image_urls'] = urljoin_rfc(base_url, relative_url)
      File "/Library/Python/2.6/site-packages/Scrapy-0.12.0.2541-py2.6.egg/scrapy/utils/url.py", line 37, in urljoin_rfc
        unicode_to_str(ref, encoding))
      File "/Library/Python/2.6/site-packages/Scrapy-0.12.0.2541-py2.6.egg/scrapy/utils/python.py", line 96, in unicode_to_str
        raise TypeError('unicode_to_str must receive a unicode or str object, got %s' % type(text).__name__)
    exceptions.TypeError: unicode_to_str must receive a unicode or str object, got list

2011-06-28 17:18:15-0400 [namastecopy2] DEBUG: Crawled (200) <GET http://www.namastefoods.com/products/cgi-bin/products.cgi?Function=show&Category_Id=4&Id=1> (referer: None)
2011-06-28 17:18:15-0400 [namastecopy2] ERROR: Spider error processing <http://www.namastefoods.com/products/cgi-bin/products.cgi?Function=show&Category_Id=4&Id=1> (referer: <None>)
    Traceback (most recent call last):
      File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/internet/base.py", line 1137, in mainLoop
        self.runUntilCurrent()
      File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/internet/base.py", line 757, in runUntilCurrent
        call.func(*call.args, **call.kw)
      File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/internet/defer.py", line 243, in callback
        self._startRunCallbacks(result)
      File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/internet/defer.py", line 312, in _startRunCallbacks
        self._runCallbacks()
    --- <exception caught here> ---
      File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/internet/defer.py", line 328, in _runCallbacks
        self.result = callback(self.result, *args, **kw)
      File "/***/***/***/***/***/***/spiders/namaste_copy2.py", line 30, in parse
        item['image_urls'] = urljoin_rfc(base_url, relative_url)
      File "/Library/Python/2.6/site-packages/Scrapy-0.12.0.2541-py2.6.egg/scrapy/utils/url.py", line 37, in urljoin_rfc
        unicode_to_str(ref, encoding))
      File "/Library/Python/2.6/site-packages/Scrapy-0.12.0.2541-py2.6.egg/scrapy/utils/python.py", line 96, in unicode_to_str
        raise TypeError('unicode_to_str must receive a unicode or str object, got %s' % type(text).__name__)
    exceptions.TypeError: unicode_to_str must receive a unicode or str object, got list

2    011-06-28 17:18:15-0400 [namastecopy2] INFO: Closing spider (finished)
2011-06-28 17:18:15-0400 [namastecopy2] INFO: Spider closed (finished)

谢谢。-TM


From Scrapy 文档 https://doc.scrapy.org/en/latest/intro/tutorial.html?highlight=relative#following-links:

def parse(self, response):
    # ... code ommited
    next_page = response.urljoin(next_page)
    yield scrapy.Request(next_page, self.parse)

那是,response对象有一个方法可以做到这一点。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python Scrapy:将相对路径转换为绝对路径 的相关文章

随机推荐

  • 使 django 中的内联表单集成为必需

    我是 django 的新手 到目前为止 我使用的是 symfony PHP 框架 我的问题是这样的 我有一个模型事件和模型日期 日期有一个事件的外键 因此事件可以 或应该 有一个或多个日期 现在我想要一个表单来创建事件 并且该表单应包含一个
  • 将 Linq 表达式转换为 SQL Server 查询

    我正在使用一些 crm 框架 该框架没有任何内部 orm 并且不使用实体框架 仅使用纯 sql 查询 我在数据库中的每个表都有实体 所以我有例如 public class Customer public string FirstName g
  • 分支和文件夹的 gitolite 权限

    在 gitolite 我想要 developers能够推送到除以下之外的任何分支master I want user1能够推送到任何分支 包括master 除了不是某个目录master 我该怎么做呢 这应该解决以下两个问题 repo are
  • 为什么Java中没有多重继承,但允许实现多个接口?

    Java 不允许多重继承 但它允许实现多个接口 为什么 因为接口只指定what班级正在做 而不是how它正在这样做 多重继承的问题是两个类可能定义不同的方式做同样的事情 并且子类无法选择选择哪一个
  • C++ 类型特征

    我知道它们对有关您实例化它们的类型的信息进行编码 但是它们是如何工作的 比如说 类型特征std is class 它是如何工作的 所有的实现看起来都像是空的结构 我必须承认我正在摸不着头脑 这些名字看起来足够具有描述性 所以我能理解它们的意
  • 将textView和图像对齐在同一行JAVA [关闭]

    Closed 这个问题需要调试细节 help minimal reproducible example 目前不接受答案 我创建了Food使用下面的代码选项卡 JTabbedPane tabbedPane new JTabbedPane JT
  • 为什么带有 unsigned long long 参数的 std::bitset 构造函数未标记为显式?

    标准库类模板std bitset
  • 如何在 Watson Assistant 上切换技能?

    目前 在 IBM Watson Assistant 中 您只能向助理分配一项技能 如何以编程方式交换助手的主要技能 未来的计划是让 Assistant 支持多种技能以及自定义技能 暂时作为数据 henrik https stackoverf
  • 基于两列值的VLOOKUP

    我有一个表 其中一列包含用户 ID 这些被多次输入以显示特定主题的结果 ID Topic Pass Fail 71086686 Science P 71086686 Maths P 71086686 Tech P 71086686 ICT
  • 为什么不使用 sshrc 中设置的 $PATH?

    我正在尝试在 OS X 服务器上通过 ssh 设置 svn 为了做到这一点 我读到我需要一个包装器来设置 umask 并 在我的例子中 设置存储库根 一种快速而肮脏的方法是重命名 usr bin svnserve并将包装器脚本放置在该位置
  • 将跨度值存储到 JavaScript 变量中

    我正在尝试编写 javascript 它将遍历一个跨度 获取其值 并将其存储在可用于执行算术的变量中 span class ServerData 30 span span class ServerData 6 span 关于以上两行 我的功
  • 如何删除Postman中的会话cookie?

    我正在 Postman 中测试我的 API 但在模拟时遇到问题log out If I do a call to delete the session cookie the session cookie is still there aft
  • 如何在 mongodb 中对数组进行 AND 查询?

    我有一个带有标签的数组 它是文档的一部分 例如 红 绿 蓝 白 黑 现在我想找到所有有红色和蓝色的文档 使用 all 条件查找同时匹配 红色 和 蓝色 条件的记录 db my collection find tags all red blu
  • 公共还是私人?

    我真的不明白为什么将成员变量和成员函数设为私有通常是一种好的做法 是为了防止人们搞砸事情 更多的是为了组织工具吗 基本上 是的 这是为了防止人们搞砸事情 封装 信息隐藏 是您正在寻找的术语 通过仅向外界发布最少的信息 您可以根据需要自由地更
  • 角度2:语法错误:意外的标记<(...)

    我知道 这个问题已经被问过 但我找不到适合我的特定情况的解决方案 我无法理解错误的真正原因 我有一个运行良好的 angularjs2 应用程序 现在我想导入marked图书馆 我做了什么 npm install marked tsd ins
  • 如何避免按后退按钮/键返回登录布局?

    我想为我的研究所创建一个应用程序 问题是 我的应用程序将有两种布局 登录和仪表板 学生可以正确填写登录表单 进入仪表板 按下按钮以及填写其他字段 但是 如果用户随后按下后退按钮 则不应返回到登录屏幕 而应保留在仪表板中 或者如果失败 则退出
  • Linux 上共享内存的生命周期是多长

    我正在使用 ftok shmget shmat shmdt 函数在 Linux 上创建 写入和读取共享段 如果我写入一个程序中的段 然后退出 然后稍后从另一个程序中读取该段 我会惊讶地发现数据仍然存在 我预计当共享一个段的最后一个进程执行
  • Logstash 输出到文件并忽略编解码器

    请有人向我解释一下 为什么logstash 一直忽略我正在尝试设置的 codec gt plain gt format 设置 我正在使用的 cfg 文件 input gelf host gt some ip port gt 12201 ou
  • 您可以播放 iPod 库中的视频吗?

    iOS4 中是否可以播放 iPod 库中的视频 或者仍然仅限于音频 我找不到任何明确的答案 但 SDK 似乎不允许视频 不 你不能那样做 检查 iPod Library Access 编程指南 它说 iPod 库访问仅适用于基于音频的媒体项
  • Python Scrapy:将相对路径转换为绝对路径

    我根据下面的伟大人士提供的解决方案修改了代码 我收到代码下方显示的错误 from scrapy spider import BaseSpider from scrapy selector import HtmlXPathSelector f