设置
我有来自 this page 的下一页按钮元素,
<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 <span aria-hidden="true" role="presentation">»</span></button>
</li>
我需要获取data-href
属性中的url。
代码
在 scrapy shell 中使用以下简单的 xpath 到按钮元素,
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
属性去了哪里?
如何获取url?
最佳答案
data-href
属性很可能是由浏览器中运行的某些 JavaScript 代码计算得出的。如果您查看此页面的原始源代码(浏览器中的“查看源代码”选项),您将不会在那里找到该属性。
您在开发人员工具上看到的输出是浏览器渲染的 DOM,因此您可以预期浏览器 View 与 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
关于python - Href 在 scrapy 结果中不可见,但在 html 中可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53337700/