爬虫小demo

6次阅读

共计 1346 个字符,预计需要花费 4 分钟才能阅读完成。

爬取的数据存入 Excel 表格

demo.py:

import requests    #requests 是 HTTP 库
import re
from openpyxl import workbook  # 写入 Excel 表所用
from openpyxl import load_workbook  # 读取 Excel 表所用
from bs4 import BeautifulSoup as bs   #bs: 通过解析文档为用户提供需要抓取的数据
import os
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') #改变标准输出的默认编码


#我们开始利用 requests.get()来获取网页并利用 bs4 解析网页:def getData(src):

    html = requests.get(src).content    # requests.get(src) 返回的是状态码 <Response [200]>,加上.content 以字节形式(二进制返回数据。和前端一样,分为 get post 等  http://www.cnblogs.com/ranxf/p/7808537.html
    soup = bs(html,'lxml')   # lxml 解析器解析字节形式的数据,得到完整的类似页面的 html 代码结构的数据
    print(soup)

    global ws
    Name = []
    Introductions = []
    introductions = soup.find_all("a",class_="book-item-name")
    nameList = soup.find_all("a",class_="author")
    print (nameList)
    for name in nameList:
        print (name.text)
        Name.append(name.text)
    for introduction in introductions:
        Introductions.append(introduction.text)
    for i in range(len(Name)):
        ws.append([Name[i],Introductions[i]])

if __name__ == '__main__':
    #   读取存在的 Excel 表测试
    #     wb = load_workbook('t est.xlsx') #加载存在的 Excel 表
    #     a_sheet = wb.get_sheet_by_name('Sheet1') #根据表名获取表对象
    #     for row in a_sheet.rows: #遍历输出行数据
    #         for cell in row: #每行的 每一个单元格
    #             print cell.value,

    #  创建 Excel 表并写入数据
    wb = workbook.Workbook()  # 创建 Excel 对象
    ws = wb.active  # 获取当前正在操作的表对象
    # 往表中写入标题行, 以列表形式写入!ws.append(['角色名字', '票数'])
    src = 'http://www.lrts.me/book/category/3058'
    getData(src)
    wb.save('qinshi.xlsx')  # 存入所有信息后,保存为 filename.xlsx


执行:python demo.py

效果 生成一个 qinshi.xlsx 文件

正文完
 0