scrpay - 爬取倾听fm 的排行榜 简单案例 | xpath 的使用 | extract_first() 函数的使用 | 获取下一页 链接 href
1. 爬取代码
import scrapy class FmSpider(scrapy.Spider): name = 'fm' allowed_domains = ['qingting.fm'] start_urls = ['https://m.qingting.fm/rank/'] def parse(self, response): resp_list = response.xpath('//div[@class="rank-list"]/a') for temp in resp_list: id = temp.xpath('.//div[@class="badge"]/text()').extract_first() img_url = temp.xpath('./img[@class="cover"]/@src').extract_first() title = temp.xpath('.//div[@class="title"]/text()').extract_first() dianji = temp.xpath('.//div[@class="info"]/div[1]//text()').extract_first() # print(id, img_url, title, dianji) #使用管道 yield { 'id': id, 'img_url': img_url, 'title': title, 'dianji': dianji, }
2.pipelinges.py 文件代码
from itemadapter import ItemAdapter class MyspiderPipeline: def process_item(self, item, spider): print('------------------------------', item)
注意 :
response.xpath('//div[@class="rank-list"]/a') # 可以直接对结果使用xpath
dianji.extract_first() # 可以直接获取列表中的文字
3. 获取下一页 链接
文章的链接: http://tech.huanqiu.com/science/2018-02/11605853_4.html 从上面我们可以看到,如果仅仅用xpath获取下一页的链接 例如: //div[@id="pages"]/a[@class="a1"][text()="下一页"]/@href 就会在第四页的时候重复获取相同的链接,我们通过观察可以发现一些规律: 所在的页码是在与链接a标签同级的span标签里面,这个时候我们可以采用兄弟结点,来解决这个问题, //div[@id="pages"]/span/following-sibling::a[text()!="下一页"]/@href 说明: 1 获取到span标签的下一个兄弟结点a标签 (following-sibling::a) 2 另它的text内容不为"下一页" ([text()!="下一页"]) 3 再取这个a标签的href属性 (@href) 这样在第四页的时候获取到的链接为Null , 就不会重复获取下一页的链接了