【问题标题】:Scrapy cannot find inside <div> tagsScrapy 在 <div> 标签内找不到
【发布时间】:2020-01-20 05:37:29
【问题描述】:

美好的一天。我目前正在编写一个 Scrapy 程序来抓取一个新闻网站。我是 Scrapy 的初学者,我遇到了一个无法在我的代码中取得进展的障碍。

我目前尝试抓取的网站是https://www.thestar.com.my/news/nation

在页面的 html 标签内,有一个 div 标签,带有 class="row list-listing"。我试图在 div 标记内获取 paragraph 标记,但不知何故 Scrapy 似乎无法找到标签。

我检查了所有未关闭的标签,但它们似乎都已关闭。那么为什么 Scrapy 无法获取这个标签呢? Scrapy 可以获取的最内部标签是 div class="sub-section-list",它在 div class="row list-listing"

之外

另外,当我获取 div class="sub-section-list" 标签时,它只提取这些 html 标签:

"<div class=""sub-section-list"">
     <div class=""button-view btnLoadMore"" style=""margin: 10px auto 15px;"">
         <a id=""loadMorestories"">Load more </a>
     </div>
 </div>"

检查网站时,我需要这些标签

Website Tag

我将包含我的基本代码。我才刚刚开始这个项目,所以自从这个问题以来我没有取得任何进展。

import scrapy


class WebCrawl(scrapy.Spider):
    name = "spooder"
    allowed_domains = ["thestar.com.my"]
    start_urls = ["https://www.thestar.com.my/news/nation"]

    def parse(self, response):
        text = response.xpath("//div[@class='sub-section-list']").extract()
        yield {
            'text' : text
        }

如果我忘记添加任何其他必要的东西,请告诉我。任何帮助将不胜感激。

【问题讨论】:

    标签: python html scrapy


    【解决方案1】:

    正如 Wim 所说,页面是动态加载的,所以有 a few options。 使用 Firefox 开发人员工具,看起来内容是从以下位置检索的:

    https://cdn.thestar.com.my/Content/Data/parsely_data.json
    

    所以你可以直接加载 json 并从那里得到你想要的。比如:

    import scrapy
    import json
    
    class WebCrawl(scrapy.Spider):
        name = "spooder"
        allowed_domains = ["thestar.com.my"]
        start_urls = ["https://cdn.thestar.com.my/Content/Data/parsely_data.json"]
    
        def parse(self, response):
            yield from json.loads(response.text)['data']
    

    当然,这可能不是您想要的,但也许这是一个好的开始?

    (请注意,上面的代码对于它的作用来说太过分了,但是如果你要开始一些抓取,你可以从那里开始工作)

    【讨论】:

    • 是的。您的代码对启动这个问题非常有帮助,让我继续前进。非常感谢您的帮助。
    【解决方案2】:

    内容是动态加载的,因此如果不渲染页面,您将无法像这样使用 xpath。似乎文章正文存在于html中,您可以通过以下方式获取:

    import json
    script = response.xpath(
      "//script[contains(text(), 'var listing = ')]/text()"
    ).extract_first()
    
    first_index = script.index('var listing = ') + len('var listing = ')
    last_index = script.index('};') + 1
    listings = json.loads(script[first_index:last_index])
    articles = [article['article_body'] for article in listings['data']] 
    

    【讨论】:

    • 哇,我不知道你可以通过这个提取数据。谢谢您的帮助。这非常有帮助:)
    猜你喜欢
    • 1970-01-01
    • 2020-08-18
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多