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

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

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

这次咱们用 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 入门 感激关注

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理