python爬虫之豆瓣首页图片爬取

网址:https://movie.douban.com/

python 复制代码
import requests
from lxml import etree
import re
url = 'https://movie.douban.com'
headers = {
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.289 Safari/537.36'
}
session = requests.session()
response = session.get(url,headers = headers)
# response.encoding='utf-8'
# response.encoding = response.apparent_encoding
index_url = 'https://movie.douban.com'
res = session.get(index_url,headers=headers)
# print(res.text)
# 输出:页面源代码
tree = etree.HTML(res.text)
# print(tree)
# 输出:<Element html at 0x186fa6a3100>
img_all = tree.xpath('//img')
# print(img_all)
for i in img_all:
    img = etree.tostring(i, encoding='UTF-8').decode('UTF-8')
    # 得到所有的img标签
    # print(img)
    # <img src="https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2900931370.jpg" alt="&#x5C0F;&#x884C;&#x661F;&#x730E;&#x4EBA;" rel="nofollow" class=""/>
    img_url = tree.xpath('//img/@src')
    # img_name = tree.xpath('//img/@alt')
    # print(img_url,img_name)
    # 输出:许多个列表
    for i in img_url:
        # print(i)
        last_str = i.split('/')[-1]
        # print(last_str)
        # 输出:多个p2900931370.jpg  p2901057189.jpg
        every_name = last_str.split('.')[0]
        # print(every_name)
        # 输出:多个p2900931370  p2901057189
        res_url = session.get(i,headers=headers)
        with open(f'./img/{every_name}.jpg','wb') as f:
            f.write(res_url.content)

运行结果:

相关推荐
fs哆哆1 分钟前
在VB.net中,用正则表达式方法清除干扰符号方法
开发语言·正则表达式·c#·.net
Nina_7175 分钟前
Day 48
python
工业互联网专业8 分钟前
基于Python的热门微博数据可视化分析-Flask+Vue
vue.js·python·flask·毕业设计·源码·课程设计·微博数据可视化
嵌入式@秋刀鱼14 分钟前
《 第三章-招式初成》 C++修炼生涯笔记(基础篇)程序流程结构
linux·开发语言·数据结构·c++·笔记·visual studio code
shenyan~23 分钟前
关于 WASM: WASM + JS 混合逆向流程
开发语言·javascript·wasm
q5673152326 分钟前
Linux搭建爬虫ip与私有IP池教程
linux·爬虫·tcp/ip
Spider_Man29 分钟前
让AI“动手”帮你查股票?一文带你玩转大模型 FunctionCall!
python·llm·openai
梦境虽美,却不长43 分钟前
C语言 学习 文件操作(开关,读写,定位,大小)操作 2025年6月8日12:19:24
c语言·开发语言·学习
nvvas1 小时前
Python Selenium固定端口测试chrome浏览器绕过登录验证
chrome·python·selenium
Charlotte_jc1 小时前
完美解决openpyxl保存Excel丢失图像/形状资源的技术方案
开发语言·python·excel·openpyxl