2401_83358335 2024-07-10 16:58 采纳率: 50%
浏览 16
已结题

scrapy抓取酷狗热榜top500的歌曲名称和作者

请问一下,我需要用python,scrapy框架爬取图二的歌曲名和作者名,图一是我当前的代码,图三是酷狗网页版F12查看到的源代码但是多次尝试之后都是提示表达式无效,有没有高人解答一下
终端返回完整日志在最后

img

img

img


```python
2024-07-10 16:12:56 [scrapy.utils.log] INFO: Scrapy 2.8.0 started (bot: zzh)
2024-07-10 16:12:56 [scrapy.utils.log] INFO: Versions: lxml 4.9.3.0, libxml2 2.10.4, cssselect 1.1.0, parsel 1.6.0, w3lib 1.21.0, Twisted 22.10.0, Python 3.11.5 | packaged by Anaconda, Inc. | (main, Sep 11 2023, 13:26:23) [MSC v.1916 64 bit (AMD64)], pyOpenSSL 23.2.0 (OpenSSL 3.0.12 24 Oct 2023), cryptography 41.0.3, Platform Windows-10-10.0.22621-SP0
2024-07-10 16:12:56 [scrapy.crawler] INFO: Overridden settings:
{'BOT_NAME': 'zzh',
 'COOKIES_ENABLED': False,
 'FEED_EXPORT_ENCODING': 'utf-8',
 'NEWSPIDER_MODULE': 'zzh.spiders',
 'REQUEST_FINGERPRINTER_IMPLEMENTATION': '2.7',
 'SPIDER_MODULES': ['zzh.spiders'],
 'TWISTED_REACTOR': 'twisted.internet.asyncioreactor.AsyncioSelectorReactor'}
2024-07-10 16:12:56 [asyncio] DEBUG: Using selector: SelectSelector
2024-07-10 16:12:56 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor
2024-07-10 16:12:56 [scrapy.utils.log] DEBUG: Using asyncio event loop: asyncio.windows_events._WindowsSelectorEventLoop
2024-07-10 16:12:56 [scrapy.extensions.telnet] INFO: Telnet Password: 018a58d45a1fe1e6
2024-07-10 16:12:56 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.logstats.LogStats']
2024-07-10 16:12:56 [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.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2024-07-10 16:12:56 [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']
2024-07-10 16:12:56 [scrapy.middleware] INFO: Enabled item pipelines:
['zzh.pipelines.ZzhPipeline']
2024-07-10 16:12:56 [scrapy.core.engine] INFO: Spider opened
2024-07-10 16:12:57 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2024-07-10 16:12:57 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2024-07-10 16:12:57 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (301) to <GET https://www.kugou.com/> from <GET http://www.kugou.com/>
2024-07-10 16:12:57 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.kugou.com/> (referer: None)
2024-07-10 16:12:57 [scrapy.core.scraper] ERROR: Spider error processing <GET https://www.kugou.com/> (referer: None)
Traceback (most recent call last):
  File "D:\Anaconda\Lib\site-packages\parsel\selector.py", line 254, in xpath
    result = xpathev(query, namespaces=nsp,
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "src/lxml/etree.pyx", line 1600, in lxml.etree._Element.xpath
  File "src/lxml/xpath.pxi", line 305, in lxml.etree.XPathElementEvaluator.__call__
  File "src/lxml/xpath.pxi", line 225, in lxml.etree._XPathEvaluatorBase._handle_result
lxml.etree.XPathEvalError: Invalid expression

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\Anaconda\Lib\site-packages\scrapy\utils\defer.py", line 257, in iter_errback
    yield next(it)
          ^^^^^^^^
  File "D:\Anaconda\Lib\site-packages\scrapy\utils\python.py", line 312, in __next__
    return next(self.data)
           ^^^^^^^^^^^^^^^
  File "D:\Anaconda\Lib\site-packages\scrapy\utils\python.py", line 312, in __next__
    return next(self.data)
           ^^^^^^^^^^^^^^^
  File "D:\Anaconda\Lib\site-packages\scrapy\core\spidermw.py", line 104, in process_sync
    for r in iterable:
  File "D:\Anaconda\Lib\site-packages\scrapy\spidermiddlewares\offsite.py", line 28, in <genexpr>
    return (r for r in result or () if self._filter(r, spider))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Anaconda\Lib\site-packages\scrapy\core\spidermw.py", line 104, in process_sync
    for r in iterable:
  File "D:\Anaconda\Lib\site-packages\scrapy\spidermiddlewares\referer.py", line 353, in <genexpr>
    return (self._set_referer(r, response) for r in result or ())
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Anaconda\Lib\site-packages\scrapy\core\spidermw.py", line 104, in process_sync
    for r in iterable:
  File "D:\Anaconda\Lib\site-packages\scrapy\spidermiddlewares\urllength.py", line 27, in <genexpr>
    return (r for r in result or () if self._filter(r, spider))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Anaconda\Lib\site-packages\scrapy\core\spidermw.py", line 104, in process_sync
    for r in iterable:
  File "D:\Anaconda\Lib\site-packages\scrapy\spidermiddlewares\depth.py", line 31, in <genexpr>
    return (r for r in result or () if self._filter(r, response, spider))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Anaconda\Lib\site-packages\scrapy\core\spidermw.py", line 104, in process_sync
    for r in iterable:
  File "C:\Users\hp\Desktop\小学期‘\zzh\zzh\spiders\kugou.py", line 11, in parse
    item['number'] = response.xpath("//div@[id='rankWrap']/ul/span@[class='pc_temp_num']").extract()
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Anaconda\Lib\site-packages\scrapy\http\response\text.py", line 144, in xpath
    return self.selector.xpath(query, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Anaconda\Lib\site-packages\parsel\selector.py", line 260, in xpath
    six.reraise(ValueError, ValueError(msg), sys.exc_info()[2])
 'downloader/response_status_count/301': 1,
 'elapsed_time_seconds': 0.304636,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2024, 7, 10, 8, 12, 57, 444910),
 'httpcompression/response_bytes': 697498,
 'httpcompression/response_count': 1,
 'log_count/DEBUG': 5,
 'log_count/ERROR': 1,
 'log_count/INFO': 10,
 'response_received_count': 1,
 'scheduler/dequeued': 2,
 'scheduler/dequeued/memory': 2,
 'scheduler/enqueued': 2,
 'scheduler/enqueued/memory': 2,
 'spider_exceptions/ValueError': 1,
 'start_time': datetime.datetime(2024, 7, 10, 8, 12, 57, 140274)}
2024-07-10 16:12:57 [scrapy.core.engine] INFO: Spider closed (finished)

```

  • 写回答

23条回答 默认 最新

  • 专家-赤兔[在线] 全栈领域优质创作者 2024-07-10 16:58
    关注

    引自免费微信小程序:皆我百晓生

    从你给出的错误信息来看,问题似乎出在Scrapy的XPath表达式上。具体来说,错误提示是“Invalid expression”,意味着你的XPath表达式有误。

    你的XPath表达式是:

    "//div@[id='rankWrap']/ul/span@[class='pc_temp_num']"
    

    这个表达式看起来是想从页面中选择具有特定id和class的div和span元素。然而,这个表达式中的语法可能有些问题。你应该使用点号(.)来访问元素的属性,而不是使用@符号。此外,你可能需要确保你的XPath表达式正确地指向了你想要抓取的元素。根据给出的HTML结构,你可以尝试以下的XPath表达式:

    "//div[id='rankWrap']/ul/li/span[class='pc_temp_num']"
    

    然后你可以使用这个修正后的XPath表达式来提取你想要的数据,如下所示:

    item['number'] = response.xpath("//div[id='rankWrap']/ul/li/span[class='pc_temp_num']").extract_first()
    

    另外,由于.extract_first()方法只返回匹配到的第一个元素,如果你的网页结构中每个歌曲都有一个对应的pc_temp_num元素,你可能需要遍历所有的匹配结果。这就需要使用.re()方法或者.getall()方法(取决于你使用的Scrapy版本)。这是一个使用.re()方法的例子:

    import re
    item['number'] = response.xpath("//div[id='rankWrap']/ul/li").re(r'.*?(\d+)')  # 假设数字是连续的,使用正则表达式提取数字部分
    

    注意这里的正则表达式 \d+ 是用来匹配数字的。如果数字的格式有特殊变化,可能需要调整正则表达式来适应你的需求。最后别忘了处理可能出现的空结果或者没有匹配到的情况。希望这些能帮到你!

    评论 编辑记录

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 7月11日
  • 创建了问题 7月10日

悬赏问题

  • ¥15 咨询一下有关于王者荣耀赢藏战绩
  • ¥100 求购一套带接口实现实习自动签到打卡
  • ¥50 MacOS 使用虚拟机安装k8s
  • ¥500 亚马逊 COOKIE我如何才能实现 登录一个亚马逊账户 下发新 COOKIE ..我使用下发新COOKIE 导入ADS 指纹浏览器登录,我把账户密码 修改过后,原来下发新COOKIE 不会失效的方式
  • ¥20 玩游戏gpu和cpu利用率特别低,玩游戏卡顿
  • ¥25 oracle中的正则匹配
  • ¥15 关于#vscode#的问题:把软件卸载不会再出现蓝屏
  • ¥15 vimplus出现的错误
  • ¥15 usb无线网卡转typec口
  • ¥30 怎么使用AVL fire ESE软件自带的优化模式来优化设计Soot和NOx?