ITPub博客

首页 > 应用开发 > > python爬取贴吧网页源代码

python爬取贴吧网页源代码

作者:兔子爱喝奶茶 时间:2019-10-18 09:39:07 0 删除 编辑

#本代码作用:爬取贴吧的页面信息

'''观察发现在百度贴吧搜索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

测试结果第一页的网址确实如此

'''

如下图所示:

代码如下:

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

运行结果如下图所示:

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69918097/viewspace-3151294/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-26

  • 博文量
    1470
  • 访问量
    11222