关于python:15python爬取百度贴吧excel存储

3次阅读

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

让咱们爬取百度贴吧游览信息,看看哪些地方是大家游览关注的热点。

不要问我这个十一去哪儿游览了,我还在家没日没夜的码代码。

这次咱们用 urllib 爬取页面,再用 BeautifulSoup 提取有用信息,最初用 xlsxwriter 把获取的信息 写入到 excel 表

一、用到技术

  • python 根底
  • xlsxwriter 用来写入 excel 文件的
  • urllib python 内置爬虫工具
  • BeautifulSoup解析提取数据

二、指标页面

https://tieba.baidu.com/f?kw=%E6%97%85%E6%B8%B8&ie=utf-8&pn=0

三、后果

四、装置 必要的库

  • win+R 关上运行
  • 输入 cmd 进入控制台
  • 别离装置beautifulsoup4,lxml,xlsxwriter
pip install   lxml
pip install   beautifulsoup4
pip install   xlsxwriter 

五、剖析页面

1. 页面法则

咱们单击分页按钮,拿到页面最初一个参数的法则
第二页:https://tieba.baidu.com/f?kw= 游览 &ie=utf-8&pn= 50
第三页:https://tieba.baidu.com/f?kw= 游览 &ie=utf-8&pn= 100
第四页:https://tieba.baidu.com/f?kw= 游览 &ie=utf-8&pn= 150

2. 页面信息

游览信息列表
关上网页 https://tieba.baidu.com/f?kw= 游览 &ie=utf-8&pn= 50
按键盘 F12 键或者 鼠标右键 ” 查看元素 ”(我用的谷歌 chrome 浏览器)

发现所有游览列表都有个独特的 class 类名j_thread_list

作者与创立工夫
作者的 class 为frs-author-name, 创立工夫的 class 为is_show_create_time

题目
题目的 class 为j_th_tit

六、全副代码

import xlsxwriter
# 用来写入 excel 文件的
import urllib.parse
# URL 编码格局转换的
import urllib.request
# 发动 http 申请的
from bs4 import BeautifulSoup
# css 办法解析提取信息

url='https://tieba.baidu.com/f?kw='+urllib.parse.quote('游览')+'&ie=utf-8&pn='
# 百度贴吧游览信息
# parse.quote("游览") # 后果为 %E6%97%85%E6%B8%B8

herders={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36', 'Referer':'https://tieba.baidu.com/','Connection':'keep-alive'}
# 申请头信息

data = []
# 所有爬虫的数据都寄存到 这个 data 列表外面

"""
getList 获取分页中的列表信息
url   分页地址
"""
def getList(url):

    req = urllib.request.Request(url,headers=herders)
    # 设置申请头
    response=urllib.request.urlopen(req)
    # 发动申请失去 响应后果 response

    htmlText = response.read().decode("utf-8").replace("<!--","").replace("-->","")
    # htmlText = 响应后果 read 读取.decode 转换为 utf 文本.replace 替换掉 html 中的正文
    # 咱们须要的后果在正文中,所以要先替换掉正文标签 <!-- -->

    html = BeautifulSoup(htmlText,"lxml")
    # 创立 beautifulSoup 对象

    thread_list=html.select(".j_thread_list")
    # 获取到所有的游览类别


    # 遍历游览列表
    for thread in thread_list:
        title = thread.select(".j_th_tit")[0].get_text()
        author = thread.select(".frs-author-name")[0].get_text()
        time= thread.select(".is_show_create_time")[0].get_text()
        # 提取题目,作者,事件
        print(title) # 打印标签
        data.append([title,author,time])
        # 追加到总数据中

"""
获取到所有的分页地址,最大 5 页
url 页面地址
p=5 最多 5 页
"""
def getPage(url,p=5):
    for i in range(5):
        link = url+str(i*50)
        # 再一次拼接 第 1 页 0  第 2 页 50 第 3 页 100 第 4 页 150
        getList(link)
        # 执行获取页面函数 getList

"""
写入 excel 文件
data 被写入的数据
"""
def writeExecl(data):
    lens = len(data)
    # 获取页面的长度
    workbook = xlsxwriter.Workbook('travel.xlsx')
    # 创立一个 excel 文件
    sheet = workbook.add_worksheet()
    # 增加一张工作表
    sheet.write_row("A1",["题目","作者","工夫"])
    # 写入一行题目
    for i in range(2, lens + 2):
        sheet.write_row("A"+str(i),data[i - 2])
    # 遍历 data 写入行数据到 excel
    workbook.close()
    # 敞开 excel 文件
    print("xlsx 格局表格写入数据胜利!")

"""定义主函数"""
def main():
    getPage(url,5) #获取分页
    writeExecl(data) #写入数据到 excel

# 如果到模块的名字是__main__ 执行 main 主函数
if __name__ == '__main__':
    main()

七、单词表


main        次要的
def         (define) 定义
getPage     获取页面
writeExcel  写入 excel
workbook    工作簿
sheet       表
write_row   写入行
add         增加
close       敞开
len         length 长度
data        数据
range       范畴
str(string)字符串
append      追加
author      作者
select      抉择
Beautiful   漂亮
Soup        糖
herders     头信息
response    响应
read        读
decode      编码
Request     申请
parse       解析
quote       援用

在线练习:https://www.520mg.com/it

IT 入门 感激关注

正文完
 0