ITPub博客

首页 > IT职业 > IT职场 > python爬虫如何获取表情包

python爬虫如何获取表情包

IT职场 作者:lee_lgw 时间:2021-09-11 09:52:41 0 删除 编辑

1、创建请求头,也被称为伪装浏览器

如果不添加请求头的话,可能会出现当前网站没有访问权限。

2、使用requests 网络请求库完成网站数据请求

3、获取数据后使用bs4对页面数据进行提取

需要用到一个非常好用的第三方包:bs4。

实例

import os
import requests
from bs4 import BeautifulSoup
 
if not os.path.exists('./images/'):
    os.mkdir('./images/')
 
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'
}
 
url = 'https://fabiaoqing.com/biaoqing/lists/page/1.html'
response = requests.get(url, headers=headers).text
 
'''
lxml: html解析库,因为python和html两者没有关系
python没有办法直接控制html代码
我们就需要使用lxml这个库将html代码转成python对象
    需要大家去下载 pip install lxml
'''
soup = BeautifulSoup(response, 'lxml')
img_list = soup.find_all('img', class_='ui image lazy')
for img in img_list:
img_url = img['data-original']
img_title = img['title']
print(img_url, img_title)
try:
     with open('./images/' + img_title + os.path.splitext(img_url)[-1], 'wb') as f:
        '''
        因为一张图片是二进制数据
            如果我们使用text文本形式返回
            会对文件造成破坏
            
            使用content去返回原始数据
            
        '''
         image = requests.get(img_url, headers=headers).content
         # 写入二进制数据 image这个变量是存储requests返回的二进制数据的
         f.write(image)
         print('保存成功:', img_title)
except:
     pass

以上就是python爬虫获取表情包的方法,希望对大家有所帮助。更多Python学习指路:python爬虫

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

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

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

注册时间:2016-10-22

  • 博文量
    87
  • 访问量
    13243