【问题标题】:Python: How to append a string to a scrapy list item?Python:如何将字符串附加到scrapy列表项?
【发布时间】:2015-05-02 22:26:52
【问题描述】:

我正在抓取一组 url,但它们都缺少 url 的基础,所以我想将“start_url”作为基础附加到每个抓取的 url。

蜘蛛类:

class MySpider(BaseSpider):
    name = "teslanews"
    allowed_domains = ["teslamotors.com"]
    start_urls = ["http://www.teslamotors.com/blog"]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        updates = hxs.xpath('//div[@class="blog-wrapper no-image"]')

        items = []
        for article in updates:
            item = TeslanewsItem()
            item["date"] =  article.xpath('./div/span/span/text()').extract()
            item["title"] = article.xpath('./h2/a/text()').extract()
            item["url"] = article.xpath('./h2/a/@href').extract()
            items.append(item)
        return items

我不能用base = "http://www.teslamotors.com" 做一个简单的item["url"] = article.xpath('./h2/a/@href').extract() + base

因为这会将基础添加到末尾,并且由于位于 for 循环中,并且每个字母都用逗号分隔,所以它会逐个字母地进行。

我对 Scrapy 比较陌生,所以我不知道该怎么做。

【问题讨论】:

  • 你不能改用item["url"] = base + article.xpath...吗?
  • 不。结果是h,t,t,p,:,/,/,w,w,w,.,t,e,s,l,a,... 你明白了。这是由于在 for 循环中,所以它是一个字符一个字符的。
  • 也不能以相同的格式添加到 for 循环之外。什么都没有发生。
  • 我的意思是做这个代码:item["url"] = base article.xpath('./h2/a/@href').extract()[0]。确定不行吗?
  • extract() 返回一个列表,所以你必须取列表的第一个元素!当然,我错过了那里的+ 哈哈。不客气;)

标签: python list class parsing scrapy


【解决方案1】:
from scrapy.spider import BaseSpider
from urlparse import urljoin


class MySpider(BaseSpider):
    name = "teslanews"
    allowed_domains = ["teslamotors.com"]

    base = "http://www.teslamotors.com/blog"

    start_urls = ["http://www.teslamotors.com/blog"]

    def parse(self, response):

        updates = response.xpath('//div[@class="blog-wrapper no-image"]')

        items = []
        for article in updates:
            item = TeslanewsItem()
            item["date"] = article.xpath('./div/span/span/text()').extract()
            item["title"] = article.xpath('./h2/a/text()').extract()
            item['url'] = urljoin(self.base, ''.join(article.xpath('./h2/a/@href').extract()))

        return items

【讨论】:

  • @charles-watson 有帮助吗?
猜你喜欢
  • 2012-12-05
  • 1970-01-01
  • 2021-08-11
  • 2012-09-14
  • 1970-01-01
  • 2018-08-30
  • 2011-01-04
  • 2018-09-13
  • 1970-01-01
相关资源
最近更新 更多