【问题标题】:How to extract exact tags in scrapy如何在scrapy中提取准确的标签
【发布时间】:2014-07-28 20:36:59
【问题描述】:

我为 scrapy 编写了一个类,以便像这样获取页面的内容:

#!/usr/bin/python
import html2text
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector


class StockSpider(BaseSpider):
    name = "stock_spider"
    allowed_domains = ["www.hamshahrionline.ir"]
    start_urls = ["http://www.hamshahrionline.ir/details/261730/Health/publichealth"]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
#       sample = hxs.select("WhatShouldIputHere").extract()[AndHere]
        converter = html2text.HTML2Text()
        converter.ignore_links = True
        print converter.handle(sample)

我的主要问题是我评论它的状态。

如何设置路径和提取参数?

你能指导我并给我一些例子吗?

谢谢

【问题讨论】:

标签: python html web-scraping scrapy extract


【解决方案1】:

首先你需要决定你想从页面中取出什么数据,定义一个Item类和一组Fields。然后,为了用数据填充项目字段,您需要在蜘蛛的parse() 方法中使用xpath 表达式。

这是一个从正文中检索所有段落的示例(我想是所有新闻):

from scrapy.item import Item, Field
from scrapy.spider import Spider
from scrapy.selector import Selector


class MyItem(Item):
    content = Field()


class StockSpider(Spider):
    name = "stock_spider"
    allowed_domains = ["www.hamshahrionline.ir"]
    start_urls = ["http://www.hamshahrionline.ir/details/261730/Health/publichealth"]

    def parse(self, response):
        sel = Selector(response)
        paragraphs = sel.xpath("//div[@class='newsBodyCont']/p/text()").extract()
        for p in paragraphs:
            item = MyItem()
            item['content'] = p
            yield item

请注意,我使用的是 Selector 类,因为 HtmlXPathSelector 已弃用。另外,出于同样的原因,我使用xpath() 方法而不是select()

另外,请注意,您最好在单独的 python 脚本中提取您的 Item 定义以遵循 Scrapy project structure

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2016-01-10
    • 2019-10-24
    • 2015-12-31
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    相关资源
    最近更新 更多