贴吧网页,贴吧app

首页 > 经验 > 作者:YD1662023-05-13 21:17:24

#本代码作用:爬取贴吧的页面信息 '''观察发现在百度贴吧搜索python时: 1、百度贴吧第1页网址:http://tieba.baidu.com/f?ie=utf-8&kw=python&fr=search&red_tag=p0106761335 2、百度贴吧第1页网址:http://tieba.baidu.com/f?kw=python&ie=utf-8&pn=50 3、百度贴吧第1页网址:http://tieba.baidu.com/f?kw=python&ie=utf-8&pn=100 4、百度贴吧第1页网址:http://tieba.baidu.com/f?kw=python&ie=utf-8&pn=150 观察上面的网址规律发现kw=python,即搜索关键字在ke=后面,同时网页地址最后为pn=50*(n-1), 即可得出结论第一页的网址应该为:http://tieba.baidu.com/f?kw=python&ie=utf-8&pn=0 测试结果第一页的网址确实如此 '''

如下图所示:

贴吧网页,贴吧app(1)

代码如下:

#1、下面开始导入相应的模块 import requests from bs4 import BeautifulSoup import time #2、设置请求网址,即百度贴吧 def spider1(begin,end,kw): headers={ "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/69.0.3497.100 Safari/537.36" } #设置请求头 for page in range(begin,end): #遍历range对象的数值,相当于遍历页码 pn=(page-1)*50 #将(页码的值-1)*50赋值给pn url="http://tieba.baidu.com/f?kw=" str(kw) "&ie=utf-8&pn=" str(pn) #设置网页地址为百度贴吧地址,kw为搜索关键字,pn为页码的转换值 response=requests.get(url,headers=headers) #对网站进行get请求,并伪装成浏览器进行请求 response.encoding="utf-8" #自动解析编码格式并赋值给response.encoding html=response.text #将网页源代码赋值给html print("开始打印百度贴吧关键字是:{}的第{}页网页源代码{}".format(kw,page,html)) time.sleep(1) #时间休眠1秒 print("第{}页打印完成".format(page)) #打印第多少页打印完成 spider1(1,5,"python")

运行结果如下图所示:

贴吧网页,贴吧app(2)

栏目热文

文档排行

本站推荐

Copyright © 2018 - 2021 www.yd166.com., All Rights Reserved.