「这是我参与11月更文挑战的第14天,活动详情查看:2021最后一次更文挑战」
需求
使用Scrapy+Xpath爬取图书数据,并存入数据库。
url解析
解析url,可以发现需要两个参数:
参数名 | 含义 |
---|---|
key | 查询关键字 |
page_index | 页码数量 |
编码
页面解析上,从通过抓包获得请求中,我们可以发现该网站使用静态渲染,但是,我们得到的却是一堆乱码:
针对这种情况,我们可以查看请求头,从响应头中可以发现该网站使用gbk编码返回,因此,在请求时,需要转换编码,否则就会得到像上面预览中一样乱码。
使用response.body.decode('gbk')
进行实现。
解析
解析方面,可以发现图书信息是使用ul -> li的形式进行展示的。
在解析时,可以先定位ul节点,然后通过遍历子节点的方式,获取所有图书信息所在的li节点,最后继续进行子查询,获得所有信息:
class BookSpider(scrapy.Spider):
name = 'book'
allowed_domains = ['http://search.dangdang.com/']
url = 'http://search.dangdang.com/?key={}&page_index={}'
titlie = 'Python'
index = 1
def start_requests(self):
yield scrapy.Request(url=self.url.format(self.titlie, self.index), callback=self.parse)
def parse(self, response):
try:
html = response.body.decode('gbk')
selector = scrapy.Selector(text=html)
books = selector.xpath("//*[@class='bigimg']/li")
for book in books:
item = Session1Item()
item['bTitle'] = book.xpath(".//p[@class='name']/a/@title").extract_first()
item['bAuthor'] = book.xpath(".//p[@class='search_book_author']//span[1]//a/text()").extract_first()
item['bPublisher'] = book.xpath(".//p[@class='search_book_author']//span[3]//a/text()").extract_first()
item['bDate'] = book.xpath(".//p[@class='search_book_author']//span[2]/text()").extract_first().replace('/', '')
item['bPrice'] = book.xpath(".//p[@class='price']/span[@class='search_now_price']/text()").extract_first()
item['bDetail'] = book.xpath(".//p[@class='detail']/text()").extract_first()
yield item
except Exception as e:
print(e)
self.index += 1
if self.index > 3:
# 限制数量
return
yield scrapy.Request(url=self.url.format(self.titlie, self.index), callback=self.parse)
复制代码
数据库是通过item将参数传递给pipelines进行实现,前面实验已经实现多次了,因此直接调用前面的代码,这里就不展示了,最终实现结果如下: