python爬取贴吧网页源代码

python爬取贴吧网页源代码

游戏|数码彩彩2024-03-28 7:46:34322A+A-
#本代码作用:爬取贴吧的页面信息
'''观察发现在百度贴吧搜索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
测试结果第一页的网址确实如此
'''

如下图所示:

python爬取贴吧网页源代码

 

代码如下:

#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")

运行结果如下图所示:

python爬取贴吧网页源代码

 

点击这里复制本文地址 版权声明:本文内容由网友提供,该文观点仅代表作者本人。本站(https://www.angyang.net.cn)仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件举报,一经查实,本站将立刻删除。

昂扬百科 © All Rights Reserved.  渝ICP备2023000803号-3网赚杂谈