简单的爬虫,爬取火狐主页的图片并保存到本地

使用Python的urllib.request模块和正则表达式,爬取火狐主页的图片URL,然后将其下载并保存为.jpg文件。设置User-Agent以模拟浏览器请求,避免被网站屏蔽。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#-*-  coding:utf-8 -*-
#encoding:utf8
import urllib.request
import re

import chardet
def getHtml(url):
    #html=urllib.request.urlopen(url).read()
    #charset=chardet.detect(html)
    #html=html.decode("utf-8")
    #print(charset)
    req = urllib.request.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3A101a Safari/419.3')
    response = urllib.request.urlopen(req)
    html= response.read().decode("utf-8")
    return html

def getImage(htmls):
    regx= r'https://[\S]*\.jpg'
    pattern=re.compile(regx)
    get_img=re.findall(pattern,repr(htmls))
    num=1
    for img in get_img:

        image=getHtml(img)
        print(image)
        with open(str(num)+'.jpg','w') as fp:
            fp.write(image)
            num +=1
            print("正在下载第%s张图片"%num)
    return
url="http://home.firefoxchina.cn/"
html=getHtml(url)
#print(html)
getImage(html)








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值