[python爬虫] xpath没错,但运用scrapy框架无法爬到数据

发布于 2022-09-06 21:31:10 字数 5823 浏览 13 评论 0

初学scrapy,我用python爬虫时使用scrapy框架爬取‘简书’的一些内容
运行爬虫后,爬虫就关闭了,但什么内容都没爬取到
网上类似的问答基本都说是xpath错了,导致无法抓取到数据
但我用其他方法,相同的xpath能爬取到数据
代码都在下面,求帮忙看看,谢谢

文件目录如下:

.
├── jianshu_spider
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── items.cpython-36.pyc
│   │   └── settings.cpython-36.pyc
│   ├── items.py
│   ├── middlewares.py
│   ├── pipelines.py
│   ├── settings.py
│   └── spiders
│       ├── __init__.py
│       ├── __pycache__
│       │   ├── __init__.cpython-36.pyc
│       │   └── jianshu.cpython-36.pyc
│       └── jianshu.py
├── main.py
└── scrapy.cfg

运行爬虫后的信息:

2018-03-25 15:33:20 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: jianshu_spider)
2018-03-25 15:33:20 [scrapy.utils.log] INFO: Versions: lxml 4.1.1.0, libxml2 2.9.7, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted 17.9.0, Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) - [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)], pyOpenSSL 17.5.0 (OpenSSL 1.1.0g  2 Nov 2017), cryptography 2.2.1, Platform Darwin-17.0.0-x86_64-i386-64bit
2018-03-25 15:33:20 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'jianshu_spider', 'DOWNLOAD_DELAY': 0.5, 'FEED_FORMAT': 'csv', 'FEED_URI': 'file:/Users/augustinehuang/Desktop/JIANSHU.csv', 'NEWSPIDER_MODULE': 'jianshu_spider.spiders', 'SPIDER_MODULES': ['jianshu_spider.spiders'], 'USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'}
2018-03-25 15:33:20 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.memusage.MemoryUsage',
 'scrapy.extensions.feedexport.FeedExporter',
 'scrapy.extensions.logstats.LogStats']
2018-03-25 15:33:20 [scrapy.middleware] INFO: Enabled downloader middlewares:
['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']
2018-03-25 15:33:20 [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']
2018-03-25 15:33:20 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2018-03-25 15:33:20 [scrapy.core.engine] INFO: Spider opened
2018-03-25 15:33:20 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2018-03-25 15:33:20 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2018-03-25 15:33:20 [scrapy.core.engine] INFO: Closing spider (finished)
2018-03-25 15:33:20 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'finish_reason': 'finished',
 'finish_time': datetime.datetime(2018, 3, 25, 7, 33, 20, 840120),
 'log_count/DEBUG': 1,
 'log_count/INFO': 7,
 'memusage/max': 65810432,
 'memusage/startup': 65810432,
 'start_time': datetime.datetime(2018, 3, 25, 7, 33, 20, 833221)}
2018-03-25 15:33:20 [scrapy.core.engine] INFO: Spider closed (finished)

items.py 文件代码:

from scrapy.item import Item,Field

class JianshuSpiderItem(Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    name = Field()
    # content = Field()
    # article = Field()
    # fans = Field()
    pass
    

爬虫代码编写文件:

from scrapy.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.http import Request
from jianshu_spider.items import JianshuSpiderItem

class jszt_info(CrawlSpider):
    name = 'jianshu_spider'
    start_url = ['https://www.jianshu.com/recommendations/collections?order_by=hot']

def parse(self, response):
    item = JianshuSpiderItem()
    selector = Selector(response)
    infos = selector.xpath('//div[@class="col-xs-8"]')
    for info in infos:
        try:
            name = info.xpath('div/a/h4/text()').extract()[0]
            # content = info.xpath('div/a/p/text()').extract()[0]
            # article = info.xpath('div/div/a/text()').extract()[0]
            # fans = info.xpath('div/div/text()').extract()[0]

            item['name'] = name
            # item['content'] = content
            # item['article'] = article
            # item['fans'] = fans

            yield item
        except IndexError:
            pass

    urls = ['https://www.jianshu.com/recommendations/collections?page={}&order_by=hot'.format(str(i)) for i in range(2,11)]
    for url in urls:
        yield Request(url,callback=self.parse)

setting.py文件代码:

BOT_NAME = 'jianshu_spider'

SPIDER_MODULES = ['jianshu_spider.spiders']
NEWSPIDER_MODULE = 'jianshu_spider.spiders'

USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
DOWNLOAD_DELAY = 0.5
FEED_URI = 'file:/Users/augustinehuang/Desktop/JIANSHU.csv'
FEED_FORMAT = 'csv'
ROBOTSTXT_OBEY = False

其他文件没改过

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你对谁都笑 2022-09-13 21:31:10

由于是初学scrapy,所以在确定xpath没问题后,我开始怀疑是不是代码敲错了
翻了半天书,再次回炉重做,了解了一下各个模块的属性
发现是spider文件夹下创建的爬虫模块spider类里的start_urls这个属性错了
我原本以为start_urls是自己随意定义的,所以我写成了start_url
以后学习还是要把基础打好啊

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文