首页 > 解决方案 > Href在scrapy结果中不可见但在html中可见

问题描述

设置

我有这个页面的下一页按钮元素,

<li class="Pagination-item Pagination-item--next  Pagination-item--nextSolo ">
                        <button type="button" class="Pagination-link js-veza-stranica kist-FauxAnchor" data-page="2" data-href="https://www.njuskalo.hr/prodaja-kuca?page=2" role="link">Sljedeća&nbsp;<span aria-hidden="true" role="presentation">»</span></button>
                    </li>

我需要获取data-href属性中的 url。


代码

使用以下简单的 xpath 到 scrapy shell 中的按钮元素,

response.xpath('//*[@id="form_browse_detailed_search"]/div/div[1]/div[5]/div[1]/nav/ul/li[8]/button').extract_first()                        

我找回,

'<button type="button" class="Pagination-link js-veza-stranica" data-page="2">Sljedeća\xa0<span aria-hidden="true" role="presentation">»</span></button>'

问题

data-href属性去哪了?

如何获取网址?

标签: pythonscrapyattributes

解决方案


data-href属性很可能是由浏览器中运行的某些 JavaScript 代码计算得出的。如果您查看此页面的原始源代码(浏览器中的“查看源代码”选项),您将不会在那里找到该属性。

您在开发人员工具上看到的输出是浏览器渲染的 DOM,因此您可以预期浏览器视图与 Scrapy 实际获取的内容(即原始 HTML 源)之间的差异。请记住,Scrapy 不执行任何 JavaScript 代码。

无论如何,解决这个问题的一种方法是基于data-page属性构建分页 URL:

from w3lib.url import add_or_replace_parameter
...

next_page = response.css('.Pagination-item--nextSolo button::attr(data-page)').get()
next_page_url = add_or_replace_parameter(response.url, 'page', next_page)

w3lib是一个开源库:https ://github.com/scrapy/w3lib


推荐阅读