因爲python目前不能直接處理中文路徑,必需要轉化一下,以下例子是下載圖片(名字爲中文的):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)url
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()spa