python爬取表情包
时间: 2023-08-19 17:04:41 浏览: 101
你可以使用以下代码来爬取表情包:
```python
import os
import re
import urllib.request
from bs4 import BeautifulSoup
# 设置要爬取的网页链接和用户头信息
url = "http://www.doutula.com/photo/list/?page=1"
ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36 Edg/86"
# 伪造浏览器用于 HTTP 请求的用户头
headers = {'User-Agent': ua}
# 发送HTTP请求获取网页内容
req = urllib.request.Request(url=url, headers=headers)
res = urllib.request.urlopen(req)
res_txt = res.read()
# 使用BeautifulSoup解析返回的网页内容
bs = BeautifulSoup(res_txt, 'html.parser')
# 查找并获取表情包的图片链接
div = bs.find_all('img', class_='ui image bqppsearch lazy')
# 设置保存表情包的文件夹路径
path = 'D:\表情包'
# 判断文件夹是否存在
if not os.path.exists(path):
os.mkdir(path)
print(path, '创建成功')
# 在表情包文件夹中,以输入的名称创建子文件夹
a = input('请输入你要查找的表情包名称: ')
path2 = os.path.join(path, a)
if not os.path.exists(path2):
os.mkdir(path2)
print(path2, '创建成功')
else:
print(path2, '已经存在')
# 下载表情包图片并保存到相应的文件夹中
for img in div:
img_url = img['data-original']
img_name = img['alt']
suffix = img_url.split('.')[-1]
new_img_name = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", img_name)
filename = new_img_name + '.' + suffix
file_path = os.path.join(path2, filename)
urllib.request.urlretrieve(img_url, filename=file_path)
print('表情包下载完成')
```
这段代码首先发送HTTP请求获取网页内容,然后使用BeautifulSoup解析返回的内容。接下来,通过查找特定的图片标签,获取表情包的图片链接。然后,设置保存表情包的文件夹路径,并判断文件夹是否存在,如果不存在就创建。根据用户输入的名称,在表情包文件夹中创建对应的子文件夹。最后,循环下载表情包图片并保存到相应的文件夹中。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [Python爬取表情包](https://blog.csdn.net/qq_52984184/article/details/117087328)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [简单 20 行 python 代码实现爬取表情包,麻麻再也不用担心我聊天图慌了!!](https://blog.csdn.net/weixin_46163658/article/details/109632141)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文