【问题标题】:Scrapy pipeline html parsingScrapy管道html解析
【发布时间】:2015-08-13 04:44:37
【问题描述】:

我有一个包含 3 个项目的蜘蛛:网址、标题和类别。

它们在原始 html 中加载良好,但现在我想在管道中使用 html2test 将标题和类别转换为纯文本..

这是我不正确的管道代码,有人可以帮助调试它。

谢谢

import html2text
import csv
from tutorial import settings

def write_to_csv(item):
    writer = csv.writer(open(settings.csv_file_path, 'a'), lineterminator='\n')
    writer.writerow([item[key] for key in item.keys()])


class TutorialPipeline(object):
    def process_item(self, item, spider):
        h = html2text.HTML2Text()
        h.ignore_images = True
        h.handle(item['title']).strip()
        h.handle(item['category']).strip()
        write_to_csv(item)
        return item

蜘蛛码

import scrapy
from scrapy.http import Request
from scrapy.contrib.spiders import CrawlSpider,Rule
from scrapy.contrib.linkextractors import LinkExtractor
from tutorial.items import TutorialItem

class tuto(CrawlSpider):
    name = "tuto"
    allowed_domains = ['emedicine.medscape.com']
    start_urls=["http://emedicine.medscape.com"]
    rules=(
        Rule( LinkExtractor(restrict_xpaths ='//div[@id="browsespecialties"]'),callback='follow_pages', follow=True),
    )
    def follow_pages(self, response):
        for sel in response.xpath('//div[@class="maincolbox"]//a/@href').extract():
            yield Request("http://emedicine.medscape.com/" + sel, callback = self.parse_item)

    def parse_item(self, response):
        item = TutorialItem()
        item['url'] = response.url
        item['background'] = response.xpath('//div[@class="refsection_content"]').extract()
        item['title'] = response.xpath('//h1').extract()
        yield item

【问题讨论】:

    标签: python scrapy pipeline


    【解决方案1】:

    问题是管道代码没有将 html 的结果分配给文本转换。要更新项目,您应该将进行转换的位更改为:

    ...
    item['title'] = h.handle(item['title']).strip()
    item['category'] = h.handle(item['category']).strip()
    ...
    

    【讨论】:

      【解决方案2】:

      您无需在管道中解析 HTML。

      提取蜘蛛中元素的text()

      替换:

      item['background'] = response.xpath('//div[@class="refsection_content"]').extract()
      item['title'] = response.xpath('//h1').extract()
      

      与:

      item['background'] = response.xpath('//div[@class="refsection_content"]/text()').extract()
      item['title'] = response.xpath('//h1/text()').extract()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-27
        • 2014-07-02
        • 2015-05-01
        • 2012-05-13
        相关资源
        最近更新 更多