如何从废弃的数据中去除html标记和javascript函数?

2024-09-24 06:27:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个粗糙的项目和数据,我需要的是得到刮也。你知道吗

但问题是,这些数据包含了很多不需要的东西,比如Javascript函数和其他html标记。如何摆脱它们,只获取数据?你知道吗

我的testSpider.py代码:

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from testing.items import testingItem

class TestSpider(CrawlSpider):
    name = 'testspider'
    session_id = -1
    start_urls = ["https://www.wikipedia.org/"]
    rules = ( Rule (SgmlLinkExtractor(allow=("", ),),
                callback="parse_items",  follow= True),
    )

    def __init__(self, session_id=-1, *args, **kwargs):
        super(TestSpider, self).__init__(*args, **kwargs)
        self.session_id = session_id

    def parse_items(self, response):
        sel = Selector(response)
        items = []
        item = testingItem()
        item["session_id"] = self.session_id
        item["depth"] = response.meta["depth"]
        # item["current_url"] = response.url
        # referring_url = response.request.headers.get('Referer', None)
        # item["referring_url"] = referring_url
        item["title"] = sel.xpath('//title/text()').extract()
        item["content"]=sel.xpath('content/text()').extract()
        items.append(item)
        return items



    My items.py:

    from scrapy.item import Item, Field

    class testingItem(Item):
        session_id =Field()
        depth = Field()
        current_url=Field()
        referring_url =Field()
        title=Field()
        content=Field()

Tags: fromimportselfidurlfieldresponsesession
1条回答
网友
1楼 · 发布于 2024-09-24 06:27:21

如果您不能准确地提取您需要的内容,那么您需要创建一些函数或类来为您清理数据,作为分离的部分。在解析函数中调用它。例如

你知道吗实用程序.py你知道吗

class Cleaner(object):

    def clean_html_tags(data):
        ....
        return data

    def clean_empty_space(data):
        ...
        return data

然后在解析函数中可以使用以下内容:

from spider.utils import Cleaner

...

 def parse(self, response):
    item['something'] = Cleaner.clean_html_tags(selector.xpath("//div[@class='myclass']/div/text()").extract())

相关问题 更多 >