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] 豆瓣-新书速递
[3] lxml 中文乱码