python爬虫:利用正则表达式爬取豆瓣读书首页的book
1、问题描述:
爬取豆瓣读书首页的图书的名称、链接、作者、出版日期,并将爬取的数据存储到Excel表格Douban_I.xlsx中
2、思路分析:
发送请求--获取数据--解析数据--存储数据
1、目标网址:https://book.douban.com/
2、利用requests.get()方法向豆瓣读书首页发送请求,获取首页的HTML源代码
#目标网址
targetUrl = "https://book.douban.com/"
#发送请求,获取响应
response = requests.get(targetUrl).text
3、利用正则re.findall()解析出想要的信息: Name Url Author Date
#编译成正则表达式对象,便于复用该匹配模式
pattern = re.compile('<li.*?title="(.*?)".*?href="(.*?)".*?more-meta.*?author">(.*?)</span>.*?year">(.*?)</span>.*?</li>', re.S)
results = re.findall(pattern, response)
4、将数据存储到Excel表格中
workBook = xlwt.Workbook(encoding='utf-8') #创建Excel表,并确定编码方式
sheet = workBook.add_sheet("Douban_I")
headData = ["书名", "链接", "作者", "出版日期"] #表头信息
for colNum in range(len(headData)):
sheet.write(0, colNum, headData[colNum])
raw = 1
for book in results: #书籍信息:名称、链接、作者、出版日期
# name, url, author, date = book
for column in range(len(book)):
sheet.write(raw, column, book[column].strip())
raw += 1
workBook.save(".\Douban_I.xlsx")
3、效果展示
4、完整代码:
# -* coding: utf-8 *-
# author: wangshx6
# date: 2018-11-04
# description: 爬取豆瓣读书首页的图书的名称、链接、作者、出版日期,并将爬取的数据存储到Excel表格Douban_I.xlsx中
import requests
import re
import xlwt
#目标网址
targetUrl = "https://book.douban.com/"
#发送请求,获取响应
response = requests.get(targetUrl).text
''' 利用正则表达式解析出关键内容: Name Url Author Date '''
#re.compile()是将正则字符串编译成正则表达式对象,便于复用该匹配模式
#re.S 多行匹配(换行)
pattern = re.compile('<li.*?title="(.*?)".*?href="(.*?)".*?more-meta.*?author">(.*?)</span>.*?year">(.*?)</span>.*?</li>', re.S)
results = re.findall(pattern, response)
#将数据列表存储到Excel表格Douban_I.xlsx中
workBook = xlwt.Workbook(encoding='utf-8')
sheet = workBook.add_sheet("Douban_I")
headData = ["书名", "链接", "作者", "出版日期"] #表头
for colNum in range(len(headData)):
sheet.write(0, colNum, headData[colNum])
raw = 1
for book in results:
# name, url, author, date = book
for column in range(len(book)):
sheet.write(raw, column, book[column].strip())
raw += 1
workBook.save(".\Douban_I.xlsx")