parsing - Scrapy解析分页没有下一个链接
问题描述
我正在尝试解析没有下一个链接的分页。html是亲爱的:
<div id="pagination" class="pagination">
<ul>
<li>
<a href="//www.demopage.com/category_product_seo_name" class="page-1 ">1</a>
</li>
<li>
<a href="//www.demopage.com/category_product_seo_name?page=2" class="page-2 ">2</a>
</li>
<li>
<a href="//www.demopage.com/category_product_seo_name?page=3" class="page-3 ">3</a>
</li>
<li>
<a href="//www.demopage.com/category_product_seo_name?page=4" class="page-4 active">4</a>
</li>
<li>
<a href="//www.demopage.com/category_product_seo_name?page=5" class="page-5">5</a>
</li>
<li>
<a href="//www.demopage.com/category_product_seo_name?page=6" class="page-6 ">6</a>
</li>
<li>
<span class="page-... three-dots">...</span>
</li>
<li>
<a href="//www.demopage.com/category_product_seo_name?page=50" class="page-50 ">50</a>
</li>
</ul>
</div>
对于这个 html,我尝试了这个 xpath:
response.xpath('//div[@class="pagination"]/ul/li/a/@href').extract()
or
response.xpath('//div[@class="pagination"]/ul/li/a/@href/following-sibling::a[1]/@href').extract()
有没有解析这个分页的好方法?谢谢大家。
PS:我也检查了这个答案:
解决方案
一种解决方案是抓取 x 个页面,但如果页面总数不是恒定的,这并不总是一个好的解决方案:
class MySpider(scrapy.spider):
num_pages = 10
def start_requests(self):
requests = []
for i in range(1, self.num_pages)
requests.append(scrapy.Request(
url='www.demopage.com/category_product_seo_name?page={0}'.format(i)
))
return requests
def parse(self, response):
#parse pages here.
更新
您还可以跟踪页数并执行类似的操作。a[href~="?page=2"]::attr(href)
将定位a
元素的哪个href
属性包含指定的字符串。(我目前无法测试这段代码是否有效,但这种风格的东西应该可以做到)
class MySpider(scrapy.spider):
start_urls = ['https://demopage.com/search?p=1']
page_count = 1
def parse(self, response):
self.page_count += 1
#parse response
next_url = response.css('#pagination > ul > li > a[href~="?page={0}"]::attr(href)'.format(self.page_count))
if next_url:
yield scrapy.Request(
url = next_url
)
推荐阅读
- python - 将过滤应用于删除项目的列表
- laravel - Laravel:兄弟姐妹之间的关系
- powershell - 在Powershell中将方法设置为对象的属性
- python - 如何从python遍历excel中的单元格
- django - 是否可以将不需要数据库的应用程序添加到 django
- flutter - 如何防止生产颤振应用程序在模拟器中运行?
- javascript - 如何在不添加历史记录的情况下推送到 vue-router?
- javascript - 如何导出函数和数组
- reactjs - 如何在“React.js”中的 ReactTable 行上显示手悬停
- azure - Azure webapp 运行“docker run”两次但无法部署