求Python大佬看看怎么改成分别下载这个3个html
本帖最后由 拨Q 于 2021-2-28 16:09 编辑import urllib.request
def getHtml(url):
html = urllib.request.urlopen(url).read()
return html
def saveHtml(file_name, file_content):
with open(file_name.replace('/', '_') + ".html", "wb") as f:
f.write(file_content)
aurl = "https://tech.163.com/21/0227/17/G3S0GV4B00097U7T.html"
aurl = "https://news.163.com/21/0227/18/G3S4JLIC00019K82.html"
aurl = "https://www.163.com/dy/article/G3PTGC8805504DP0.html"
html = getHtml(aurl)
saveHtml("sduview", html)
print("下载成功")
现在这样子只能下载最后一个html,怎么分别下载这3个html到本地,文件名保存和原始地址一样的文件名 变量重新赋值会覆盖前面的值,每次赋值后执行下载方法就行 本帖最后由 Paranoid丶 于 2021-2-28 01:10 编辑
把变量转为列表,然后用循环遍历列表去下载,文件名用正则匹配(我正则就只学了一点点,所以曲线实现方法是取最后一个'/'前面内容,然后用replace替换删掉,建议楼主自己看一下正则规则然后优化一下)
import urllib.request
import re
def getHtml(url):
html = urllib.request.urlopen(url).read()
return html
def saveHtml(file_name, file_content):
with open(file_name.replace('/', '_') + ".html", "wb") as f:
f.write(file_content)
aurl = ["https://tech.163.com/21/0227/17/G3S0GV4B00097U7T.html","https://news.163.com/21/0227/18/G3S4JLIC00019K82.html","https://www.163.com/dy/article/G3PTGC8805504DP0.html"]
for i in range(len(aurl)):
html = getHtml(aurl)
saveHtml(aurl.replace(re.search('.*/',aurl).group(0),'').replace('.html',''), html)
print("下载成功") 给后两个改下名就好,aurl1 aurl2 aurl3
save aurl1
...
...
你这等于是重复定义一个变量
页:
[1]