鱼C论坛

 找回密码
 立即注册
查看: 3628|回复: 14

scrapy 爬虫框架问题求助

[复制链接]
发表于 2017-8-23 20:11:43 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
目标:爬去简单网得 10到100得段子 包含作者 内容
所用库:BeautifulSoup库等一系列库
遇到的问题,不知道为什么 写入的文件是空的
spider 源代码:
# -*- coding: utf-8 -*-
import scrapy
import bs4
from bs4 import BeautifulSoup
from scrapy.http import Request  #跟进url
import re
from ..items import JiandanItem
class DuanziSpider(scrapy.Spider):
    name = 'duanzi'
    allowed_domains = ['jandan.net/duan']
    start_urls = ['http://jandan.net/duan/page-']
    end_urls='#comments'
    def parse(self, response):
        for i in range(100,300):
            url=[self.start_urls+str(i)+self.end_url]
            yield Request(url,self.get_content)

    def get_content(self, response):
        item=JiandanItem()
        soup=BeautufulSoup(response.text,'lxml')
        str_author=soup.find_all('div',class_='author')
        str_text=soup.find_all('div',class_='text')
        for i in range(len(str_author)):
            item['author']=[str_author[i].strong.get_text()]
            item['content']=[str_text[i].p.get_text()]
            
        return item
piplines 代码:
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html


class JiandanPipeline(object):
    def process_item(self, item, spider):
        return item

class Jiandaninpipeline(object):
    def open_spider(self,spider):
        self.f=open('jiandanduanzi.txt','w')

    def close_spider(self,spider):
        self.f.close()

    def process_item(self,item,spider):
        line=str(dict(item['author'])+'\n'+str(dict(item['content'])))
        self.f.fwrite(line)
        return item
  

求问大佬 那边理解错了
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-8-23 22:40:49 | 显示全部楼层
爬的时候有显示吗,是不是没激活
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-23 23:29:51 | 显示全部楼层
2017-08-23_232743.png
2017-08-23_232547.png
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2017-8-23 23:42:54 | 显示全部楼层

想问一下 怎么改才对。第一个问题我把第一个类给删了,第二个问题我不知道怎么改 是我内容筛选出问题了吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-23 23:50:22 | 显示全部楼层
颠鸾倒凤颜如玉 发表于 2017-8-23 23:42
想问一下 怎么改才对。第一个问题我把第一个类给删了,第二个问题我不知道怎么改 是我内容筛选出问题了吗 ...

自已在认真检查下是否爬到有数据吧。一步一步来
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-8-24 09:13:13 | 显示全部楼层
ba21 发表于 2017-8-23 23:50
自已在认真检查下是否爬到有数据吧。一步一步来

答主得意思是不是要调试  scrapy框架不会调试啊  有没有教程
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-8-24 13:09:45 | 显示全部楼层
ba21 发表于 2017-8-23 23:50
自已在认真检查下是否爬到有数据吧。一步一步来

答主你好 我用requests 库 和BeautufulSoup 重写了一份代码如下:
import requests
from bs4 import BeautifulSoup
def get_html(url):
    headers={'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 UBrowser/6.1.3397.16 Safari/537.36'}
    re=requests.get(url,headers=headers)
    re.raise_for_status()
    re.encoding=re.apparent_encoding
    return re.text

def cho_content(html,author,content):
    soup=BeautifulSoup(html,'html.parser')
    st_author=soup.find_all('div',class_='author')
    st_content=soup.find_all('div',class_='text')
    for i in range(len(st_author)):
        author.append(st_author[i].strong.string)
        content.append(st_content[i].p.string)

def sav_content(path,author,content):
    with open(path,'a') as f:
        for i in range(len(content)):
            f.write('%d\n'%(i+1))
            f.write('%s\n'%author[i])
            f.write('%s\n'%content[i])
        
def main():
    sta_url='http://jandan.net/duan/page-'
    author=[]
    content=[]
    path='g://duanzi.txt'
    for i in range(10,20):
        url=sta_url+str(i)+'#comments'
        html=get_html(url)
        cho_content(html,author,content)
        sav_content(path,author,content)
    print('完成')


main()
        

我怀疑是不是spider中的item搞错了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-8-24 13:10:35 | 显示全部楼层
小锟 发表于 2017-8-23 22:40
爬的时候有显示吗,是不是没激活

有显示啊
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-24 13:34:02 | 显示全部楼层

在setting里激活一下就好了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-8-24 15:32:37 | 显示全部楼层
小锟 发表于 2017-8-24 13:34
在setting里激活一下就好了

你好  能问一下 怎么激活吗 为什么我的这爬虫 爬下的数据有问题 是不是item的问题 求指教
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-24 18:56:21 | 显示全部楼层
本帖最后由 小锟 于 2017-8-24 18:58 编辑

你看看你的setting.py里面有
ITEM_PIPELINES = {
    'scrapy.pipelines.images.ImagesPipeline' : 1 ,
    'cnblogsSpider.pipelines.CnblogsspiderPipeline': 300
}
把注释去掉,
主要是'cnblogsSpider.pipelines.CnblogsspiderPipeline': 300这句,名字要写对哦
前面的IMage是下图片的不用管
捕获.PNG
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-8-24 21:06:57 | 显示全部楼层
小锟 发表于 2017-8-24 18:56
你看看你的setting.py里面有
ITEM_PIPELINES = {
    'scrapy.pipelines.images.ImagesPipeline' : 1 ,

2017-08-24 21:06:07 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: jiandan)
2017-08-24 21:06:07 [scrapy.utils.log] INFO: Overridden settings: {'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['jiandan.spiders'], 'HTTPCACHE_ENABLED': True, 'NEWSPIDER_MODULE': 'jiandan.spiders', 'BOT_NAME': 'jiandan'}
2017-08-24 21:06:07 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.logstats.LogStats',
'scrapy.extensions.telnet.TelnetConsole',
'scrapy.extensions.corestats.CoreStats']
2017-08-24 21:06:08 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
'scrapy.downloadermiddlewares.retry.RetryMiddleware',
'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
'scrapy.downloadermiddlewares.stats.DownloaderStats',
'scrapy.downloadermiddlewares.httpcache.HttpCacheMiddleware']
2017-08-24 21:06:08 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
'scrapy.spidermiddlewares.referer.RefererMiddleware',
'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-08-24 21:06:08 [scrapy.middleware] INFO: Enabled item pipelines:
['jiandan.pipelines.Jiandaninpipeline']
2017-08-24 21:06:08 [scrapy.core.engine] INFO: Spider opened
2017-08-24 21:06:08 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-08-24 21:06:08 [scrapy.extensions.httpcache] DEBUG: Using filesystem cache storage in G:\工具\爬虫类\jiandan\.scrapy\httpcache
2017-08-24 21:06:08 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2017-08-24 21:06:08 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://jandan.net/robots.txt> (referer: None) ['cached']
2017-08-24 21:06:08 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://jandan.net/duan/page-> (referer: None) ['cached']
2017-08-24 21:06:08 [scrapy.spidermiddlewares.httperror] INFO: Ignoring response <404 http://jandan.net/duan/page->: HTTP status code is not handled or not allowed
2017-08-24 21:06:08 [scrapy.core.engine] INFO: Closing spider (finished)
2017-08-24 21:06:08 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 436,
'downloader/request_count': 2,
'downloader/request_method_count/GET': 2,
'downloader/response_bytes': 5488,
'downloader/response_count': 2,
'downloader/response_status_count/200': 1,
'downloader/response_status_count/404': 1,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2017, 8, 24, 13, 6, 8, 645246),
'httpcache/hit': 2,
'httperror/response_ignored_count': 1,
'httperror/response_ignored_status_count/404': 1,
'log_count/DEBUG': 4,
'log_count/INFO': 8,
'response_received_count': 2,
'scheduler/dequeued': 1,
'scheduler/dequeued/memory': 1,
'scheduler/enqueued': 1,
'scheduler/enqueued/memory': 1,
'start_time': datetime.datetime(2017, 8, 24, 13, 6, 8, 464768)}
2017-08-24 21:06:08 [scrapy.core.engine] INFO: Spider closed (finished)


运行日志  
没用还是空的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-24 21:17:07 | 显示全部楼层
我这是没有BS4,不过功能还是照样能实现。代码就你传上
Jiandan.rar (21.57 KB, 下载次数: 2)
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-8-25 12:18:56 | 显示全部楼层
ba21 发表于 2017-8-24 21:17
我这是没有BS4,不过功能还是照样能实现。代码就你传上

你好 请问 from Jiandan.items import JiandanItem 这个功能怎么实现的 我传入就是错误
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-25 12:21:37 | 显示全部楼层
颠鸾倒凤颜如玉 发表于 2017-8-25 12:18
你好 请问 from Jiandan.items import JiandanItem 这个功能怎么实现的 我传入就是错误

导入你的items.py类
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-12-23 09:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表