python - 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 <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
属性去哪了?
如何获取网址?
解决方案
该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
推荐阅读
- autodesk-forge - Autodesk Forge - 使用 modelderivative API 从 2D Cad 绘图中提取几何数据
- json - 如何将数据从电报机器人内联键盘发送到谷歌电子表格中的特定列?
- python - 用于 Dialogflow 的 Python 中的 Fulfillment Webhook
- javascript - 为什么必须重新分配包含 setInterval 的变量才能使计数功能起作用?
- python - 尝试创建 except sr.UnknownValueError 时出错:
- c# - 通话清单
[] C# 类中的选择(字符串查询) - spring-mvc - Spring - 如何忽略/重置 BindingResult 中的一些错误?
- java - Reflections doesn't find object subtypes
- variables - Adfv2 在主管道中引用子管道变量
- java - 在 Spring Boot 中加密静态资源 ResourceHandlerRegistry