
import scrapy
from JD.items import JdItem
import json
from copy import deepcopy
class JdSpider(scrapy.Spider):
name = 'jd'
allowed_domains = ['jd.com','p.3.cn']
start_urls = ['https://book.jd.com/booksort.html']
def parse(self, response):
dt_list = response.xpath('//div[@class="m m0"]/div[2]/dl/dt')
for dt in dt_list:
item = JdItem()
item['book_category'] = dt.xpath('./a/text()').extract_first()
em_list = dt.xpath('./following-sibling::dd[1]/em')
for em in em_list:
item['s_href'] = em.xpath("./a/@href").extract_first()
item["s_category"] = em.xpath("./a/text()").extract_first()
item['s_href'] = 'https:' + item['s_href']
yield scrapy.Request(url=item['s_href'], meta={"item": deepcopy(item)}, callback=self.parse_two)
def parse_two(self, response):
item = response.meta['item']
li_list = response.xpath('//div[@id="plist"]/ul/li')
for li in li_list:
book_href = li.xpath('.//div[@class="p-img"]/a/@href').extract_first()
item['book_href'] = 'http:' + book_href
item['book_name'] = li.xpath('.//div[@class="p-name"]/a/em/text()').extract_first().strip()
item["book_img"] = li.xpath(".//div[@class='p-img']//img/@src").extract_first()
if item["book_img"] is None:
item["book_img"] = li.xpath(".//div[@class='p-img']//img/@data-lazy-img").extract_first()
item["book_img"] = "https:" + item["book_img"] if item["book_img"] is not None else None
item['book_author'] = li.xpath('.//span[@class="author_type_1"]/a/text()').extract_first()
item['book_press'] = li.xpath('.//span[@class="p-bi-store"]/a/text()').extract_first()
item['book_publication_time'] = li.xpath('.//span[@class="p-bi-date"]/text()').extract_first().strip()
book_sku = li.xpath("./div/@data-sku").extract_first()
yield scrapy.Request(
"https://p.3.cn/prices/mgets?skuIds=J_{}".format(book_sku),
meta={"item": deepcopy(item)},
callback=self.parse_book_price)
def parse_book_price(self, response):
item = response.meta["item"]
item["book_price"] = json.loads(response.body.decode())[0]["op"]
print(item)
