Scrapy 刮痧+;仅提取文本+;输出文件中的回车

Scrapy 刮痧+;仅提取文本+;输出文件中的回车,scrapy,output,character,extra,Scrapy,Output,Character,Extra,我不熟悉Scrapy,尝试从网页中提取内容,但在输出中获得了大量额外字符。见附图 如何更新代码以删除字符?我只需要从网页中提取href 我的代码: class AttractionSpider(CrawlSpider): name = "get-webcontent" start_urls = [ 'http://quotes.toscrape.com/page/1/' ] rules = () def create_dirs(dir): if not os.path.

我不熟悉Scrapy,尝试从网页中提取内容,但在输出中获得了大量额外字符。见附图

如何更新代码以删除字符?我只需要从网页中提取href

我的代码:

class AttractionSpider(CrawlSpider):
name = "get-webcontent"
start_urls = [
    'http://quotes.toscrape.com/page/1/'
]
rules = ()
def create_dirs(dir):    
    if not os.path.exists(dir):
        os.makedirs(dir)
    else:
        shutil.rmtree(dir)           #removes all the subdirectories!
        os.makedirs(dir)

def __init__(self, name=None, **kwargs):
    super(AttractionSpider, self).__init__(name, **kwargs)
    self.items_buffer = {}
    self.base_url = "http://quotes.toscrape.com/page/1/"        
    from scrapy.conf import settings
    settings.overrides['DOWNLOAD_TIMEOUT'] = 360
def write_to_file(file_name, content_list):
    with open(file_name, 'wb') as fp:
        pickle.dump(content_list, fp)

def parse(self, response):
    print ("Start scrapping webcontent....")        
    try:            
        str = ""
        hxs = Selector(response)
        links = hxs.xpath('//li//@href').extract()
        with open('test1_href', 'wb') as fp:
            pickle.dump(links, fp)
        if not links:               
            return
            log.msg("No Data to scrap")
        for link in links:
            v_url = ''.join( link.extract() )           
            if not v_url:
                continue
            else:
                _url = self.base_url + v_url
    except Exception as e:
        log.msg("Parsing failed for URL {%s}"%format(response.request.url))
        raise 

def parse_details(self, response):
    print ("Start scrapping Detailed Info....")
    try:
        hxs = Selector(response)            
        yield l_venue
    except Exception as e:
        log.msg("Parsing failed for URL {%s}"%format(response.request.url))
        raise

现在我必须说。。。很明显,你有一些Python编程的经验,很明显,你正在做官方的Scrapy docs教程,这很好,但就我的一生而言,我不知道你提供的代码片段到底是什么。但没关系,这里有几件事:

你用的是一只刮痒的爬行蜘蛛。使用十字十字轴时,如果愿意,规则将设置跟随或分页,以及在适当的正则表达式将规则与页面匹配时,在车中指向函数,然后初始化提取或逐项。这对于理解在不设置规则的情况下不能使用crossfire是绝对重要的,同样重要的是,在使用cross spider时,不能使用解析函数,因为cross spider的构建方式解析函数本身已经是一个本机内置函数。请继续阅读文档,或者只是创建一个十字爬行器,看看它如何不在解析中创建

你的代码 应该是什么样子 第二点:回顾一下我提到的关于用爬行爬行器使用parts函数的事情,你应该使用“parse-_item”;我假设您至少查看了官方文档,但总而言之,它不能使用的原因是因为爬行爬行器已经在其逻辑中使用了部分,所以通过在交叉爬行器中使用部分,您正在覆盖它拥有的本机函数,并且可能会导致各种错误和问题

这很简单;我不认为我必须继续向你展示一个片段,但请随意转到官方文档,右边写着“爬行”的地方继续向下滚动,直到你点击“爬行爬行”,它会给出一些注意事项

我的下一点是:当你从最初的部分开始,你没有(或者更确切地说,你没有)一个从解析到部分细节的回调,这让我相信,当你执行爬网时,你不会超过第一页,除此之外,如果你试图创建一个文本文件(或者你正在使用操作系统模块2写一些东西,但实际上你没有写任何东西)所以我非常困惑为什么你使用正确的函数而不是读取

我的意思是,我自己,我在很多情况下使用一个外部文本文件或CSV文件,包括多个URL,所以我不必把它放在那里,但你显然是在写或试图写一个你说是管道的文件?现在我更困惑了!但重点是我希望你很清楚如果您正在尝试创建一个文件或导出您提取的项目,可以选择导出并转换为三种已预构建的格式,即CSV JSON。但是,正如您在回复我的评论时所说,如果您确实使用管道和项目以及Porter intern,您可以根据自己的意愿创建导出格式,但如果这只是响应你需要的网址为什么要经历那么多麻烦

我的临别赠言是:再次阅读Scrapy的官方文档教程,并强调同时使用settings.py和items.py的重要性,对您很有帮助

# -*- coding: utf-8 -*-
import scrapy
import os
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from quotes.items import QuotesItem

class QcrawlSpider(CrawlSpider):
    name = 'qCrawl'
    allowed_domains = ['quotes.toscrape.com']
    start_urls = ['http://quotes.toscrape.com/']

    rules = (
        Rule(LinkExtractor(allow=r'page/.*'), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
    rurl = response.url
        item = QuotesItem()
        item['quote'] =response.css('span.text::text').extract()
        item['author'] = response.css('small.author::text').extract()
        item['rUrl'] = rurl
        yield item

    with open(os.path.abspath('') + '_' + "urllisr_" + '.txt', 'a') as a:
            a.write(''.join([rurl, '\n']))
            a.close()
当然,items.py将由您在spider中看到的条目适当地填写,但是通过包含响应URL(两个条目),我可以在给定默认的scrasty方法CSV等的情况下进行写入,或者我可以创建自己的响应URL


在这种情况下,作为一个简单的文本文件,但可能会变得相当狡猾;例如,如果您使用操作系统模块正确地写出它,您也可以,例如,我从视频托管站点创建了m3u播放列表,您可以使用自定义CSV项目导出器获得乐趣。但即使使用自定义管道,我们也可以写出你的CSV或任何你想要的自定义格式。

我从来没有见过这样的东西,哈哈,我要尝试复制你的代码,尽管我不完全知道你导入了什么模块,但我想象操作系统,当然是爬行爬行器的受人尊敬的模块,所以…这里我从scrapy.spider导入爬行爬行爬行爬行器,规则从scrapy.selector从scrapy导入HtmlXPathSelector.selector从scrapy导入selector.http从scrapy导入请求。LinkedExtractor从scrapy导入LinkedExtractor从scrapy导入日志从scrapy.http导入HtmlResponse从scrapy.pipelines.images从scrapy导入pickle.exceptions导入ImagesPipeline从scrapy.DropItem导入DropItem导入日期时间从scra导入scrapypy.contrib.pipeline.images从scrapy导入ImagesPipeline.exceptions从scrapy导入DropItem导入Selectordear God man LOL…这就是你导入的所有模块?如果你只是想得到…等等,我有一个很好的大O解释给你…希望我能分解一些苏打水,但很明显你知道一些python而不是问题ning,我只是觉得你肯定需要一些指导来了解如何使用Scrapy,但是因为你在那里做官方文档的教程,我有点担心?关于你的代码有多复杂…我的意思是,我再次看到你做了一些python pro,但是…给我15-20分钟,我会给你一个很好的答案,希望我能帮助你和其他人er人员还有一些用于数据提取的代码:links=response.css('img').xpath('@src').extract()#Image extract with open('imgs','wb')作为fp:pickle.dump(links,fp)links=response.xpath('//a[contains(@href,“Image”)]]]/img/@src')。extract()作为fp:pickle.dump(links,fp)#视频提取,open('Video','wb')为fp:pickle.dump(links,fp)links=hxs.xpath('//a[contains(@hr
class AttractionSpider(CrawlSpider):
    name = "get-webcontent"
    start_urls = ['http://quotes.toscrape.com'] # this would be cosidered a base url
    

# regex is our bf, kno him well, bassicall all pages that follow 
#this pattern ... page/.* (meant all following include no exception)
    rules = (
            Rule(LinkExtractor(allow=r'/page/.*'), follow=True),callback='parse_item'),
            )
# -*- coding: utf-8 -*-
import scrapy
import os
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from quotes.items import QuotesItem

class QcrawlSpider(CrawlSpider):
    name = 'qCrawl'
    allowed_domains = ['quotes.toscrape.com']
    start_urls = ['http://quotes.toscrape.com/']

    rules = (
        Rule(LinkExtractor(allow=r'page/.*'), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
    rurl = response.url
        item = QuotesItem()
        item['quote'] =response.css('span.text::text').extract()
        item['author'] = response.css('small.author::text').extract()
        item['rUrl'] = rurl
        yield item

    with open(os.path.abspath('') + '_' + "urllisr_" + '.txt', 'a') as a:
            a.write(''.join([rurl, '\n']))
            a.close()