python - Href 在 scrapy 结果中不可见,但在 html 中可见

标签 python scrapy attributes

设置

我有来自 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&nbsp;<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/

相关文章:

python - 检查输入 : expected input_1 to have 4 dimensions, 但获得形状为 (224, 224, 3) 的数组时出错

python difflib print 仅匹配两个字符串之间的部分

fastApi 中的 python 全局变量无法正常工作

vim - YouCompleteMe 不可用 : module 'collections' has no attribute 'Mapping'

reactjs - 从组件获取状态并将其显示为 div 内的值属性?

python - 为什么导出 GOOGLE_APPLICATION_CREDENTIALS 不适用于 `bq`?

elasticsearch - 无法创建Elasticsearch映射或使日期字段起作用

python - 如果比 Lastmod 日期更新,则抓取 url -Scrapy

python - DNS 查找失败 : address 'your.proxy.com' not found: [Errno -5] No address associated with hostname

attributes - ember,如何在多个链接中获取 "name"属性?