【问题标题】:How to extract text in a expand more button using scrapy?如何使用scrapy在展开更多按钮中提取文本?
【发布时间】:2019-05-09 08:20:07
【问题描述】:

在网址中: https://teslamotorsclub.com/tmc/threads/tesla-tsla-the-investment-world-the-2019-investors-roundtable.139047/page-2619

发布 #52365

在获取文本之前,我需要点击“展开更多”,如何获取其中的文本?有没有办法在运行蜘蛛脚本时触发展开更多以显示整体?

到目前为止我尝试过的是这个

info.xpath(".//div[@class= 'messageContent']").extract_first().replace('\n', '')

但我仍然无法获得全文

【问题讨论】:

  • 此文本为您隐藏,但所有文本都在此标记中(它不是由 javascript 更新的),因此scrapy 无需单击“展开更多”即可获取所有文本。
  • Post #52365 是第 5 个帖子,因此您必须使用 [4] 才能获得它 - xpath(".//div[@class='messageContent']")[4].extract()
  • @furas 不是这样。 XPath 索引是基于 1 的(我知道……)。
  • @Gallaecio - 也许 xpath 索引是 1-bases 但我不在 xpath 中使用 [4]。我从 python 的列表中得到 [4],从 0 开始计数。我还在 scrapy shell 中对其进行了测试,它似乎给出了预期的文本。
  • 你是对的,对不起!

标签: python web-scraping scrapy


【解决方案1】:

您可能会在末尾看到“单击以展开”文本,但仍会看到整个报价。您需要的是避免提取“点击展开”文本。

例如:

>>> response.xpath('//li[contains(@class, "message")][.//a/text()[.="#52365"]]//*[re:test(@class, "\\bquote\\b")]//text()').getall()
['CCS for model 3 coming', '\nWhile article references Europe, the North American theater will be getting a CCS adapter soon.', '\nSee article for', '\n', '\n', 'Tesla launches $190 CCS adapter for new Model S and Model X, offers retrofits for older vehicles', '\n', '\nMartian High Command', '\n', '\nPS: Text from article.', '\n', '\nUpdate: A Tesla spokesperson told us that they will make sure owners in North America will have access to all “compelling networks”, but they have nothing to announce now.']

【讨论】:

    【解决方案2】:

    正如有人在 cmets 中指出的那样,您无需单击任何内容。如果您在浏览器中打开文档检查器,您可以看到所有文本都在那里。

    您可以使用简单的 css 选择器和 for 循环检索所有消息:

    for post in sel.css('.messageList>li'): 
        text = ''.join(post.css('blockquote.messageText ::text').extract()) 
        print(text) 
        print('------')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      相关资源
      最近更新 更多