• 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、效果展示

    Douban_I.png

    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")
    
  • 相关阅读:
    [USACO 2012 Feb B]Moo
    [Atcoder ARC124] XOR Matching 2-小思维 | 暴力
    loj数列分块入门
    2019牛客暑期多校2-Partition problem深搜
    Codeforces 1554C
    [USACO 2012 Feb G]Cow Coupons----贪心&带悔(看完稳AC)
    Codeforces 220B-Little Elephant and Array-扫描线 & 树状数组
    [AtCoder ARC098] Donation| 建图 | 树型dp
    关于幂等性以及怎么实现幂等性
    【OOM】解决思路
  • 原文地址:https://www.cnblogs.com/wangshx6/p/9904104.html
Copyright © 2020-2023  润新知