Python爬虫之豆瓣-新书速递-图书解析

网页爬虫实践:抓取并解析豆瓣新书速递信息
本文详细介绍了如何使用Python、lxml和requests库从豆瓣新书速递页面抓取图书信息,并将其保存为文本文件的过程。包括HTML读取、XPath遍历以及编码问题处理。

1- 问题描述

  抓取豆瓣“新书速递”[1]页面下图书信息(包括书名,作者,简介,url),将结果重定向到txt文本文件下。


2- 思路分析[2]

  Step1 读取HTML

  Step2 Xpath遍历元素和属性


 

3- 使用工具

  Python,lxml模块,requests模块


 

4- 程序实现

 

 1 # -*- coding: utf-8 -*-
 2 from lxml import html
 3 import requests
 4 
 5 
 6 page = requests.get('http://book.douban.com/latest?icn=index-latestbook-all')
 7 tree = html.fromstring(page.text)
 8 
 9 # 若保存了html文件,可使用下面方法
10 # page = open('/home/freyr/codeHouse/python/512.htm', 'r').read()
11 # tree = html.fromstring(page)
12 
13 #提取图书信息
14 bookname = tree.xpath('//div[@class="detail-frame"]/h2/text()')    # 书名
15 author = tree.xpath('//div[@class="detail-frame"]/p[@class="color-gray"]/text()')    # 作者
16 info = tree.xpath('//div[@class="detail-frame"]/p[2]/text()')    # 简介
17 url = tree.xpath('//ul[@class="cover-col-4 clearfix"]/li/a[@href]')    # URL
18 
19 booknames = map(lambda x:x.strip(), bookname)
20 authors = map(lambda x:x.strip(), author)
21 infos = map(lambda x:x.strip(), info)
22 urls = map(lambda p: p.values()[0], url)
23 
24 with open('/home/freyr/codeHouse/python/dbBook.txt','w+') as f:
25     for book, author, info, url in zip(booknames, authors, infos, urls):
26         f.write('%s\n\n%s\n\n%s' % (book.encode('utf-8'), author.encode('utf-8'), info.encode('utf-8')))    
27         f.write('\n\n%s\n' % url )
28         f.write('\n\n-----------------------------------------\n\n\n')

PS:   1.还没有真正入手学习网页爬虫,先简单记录下。

    2.程序涉及编码问题[3]


[1] 豆瓣-新书速递

[2] lxml and Requests

[3] lxml 中文乱码 

转载于:https://www.cnblogs.com/freyr/p/4500933.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值