python3 网址路径中带中文的处理办法

本文介绍如何使用Python处理中文文件名及路径,并通过正则表达式匹配和下载图片。针对Python无法直接处理中文路径的问题,文章给出了具体的解决办法,包括使用urllib.parse.quote进行中文字符的编码。

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

由于python目前不能直接处理中文路径,必须要转化一下,如下例子是下载图片(名字为中文的):

    def getInfo(self,imageurl):
        response = urllib.request.urlopen(imageurl).read().decode('utf-8')
#         with open("text1.txt",'w',encoding='utf-8') as file:
#             file.write(response)
#         file.close()
        imageRe = re.compile(r'<a href=\"(.+)\" title')
        for image in imageRe.findall(response):
            pattern = re.compile(r'^(http://.+/)(.+[jpg|JPG])$')
            matchUrl = pattern.match(image)
            if matchUrl:
                '由于Python不能解析中文路径,所以quote一下中文字符'
                imagePath = urllib.parse.urljoin(matchUrl.group(1), urllib.parse.quote(matchUrl.group(2)))
                self.count  =self.count+1
                path = matchUrl.group(2)
                print(imageurl)
                print(image)
                'save picture'
                urllib.request.urlretrieve(imagePath, path)

    def getLink(self,url):
        response = urllib.request.urlopen(url).read().decode('utf-8')
        linkRe = re.compile(r'href="(http://.+\d+)" title=')
        for link in linkRe.findall(response):
            self.getInfo(link)
#         with open("text.txt",'w',encoding='utf-8') as file:
#             file.write(response)
#         file.close()

转载于:https://www.cnblogs.com/orientwolf/p/3857487.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值