设定
我有此页面中的下一页按钮元素,
<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
属性中的网址。
码
使用以下简单的xpath到scrapy shell中的button元素,
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句