使用LinkExtractor 提取链接
提取链接的两种方法:
- Selector
- LinkExtractor
之前的代码是使用的Selector,这里就不再做介绍了,开始LinkExtractor的学习
1.使用LinkExtractor
from scrapy.linkextractors import LinkExtractor
# 提取链接
# 下一页的url在 ul.pager > li.next > a 里面
# next_url = response.css('ul.pager li.next a::attr(href)').extract_first()
# if next_url:
# # 如果找到下一页的url,得到绝对路径,构造新的Response对象
# next_url = response.urljoin(next_url)
# yield scrapy.Request(next_url, callback=self.parse)
le = LinkExtractor(restrict_css='ul.pager li.next')
links = le.extract_links(response)
if links:
next_url = links[0].url
yield scrapy.Request(next_url,callback=self.parse)
- 描述提取规则
LinkExtractor构造器参数: