Python: teach you how to download files on the Internet

Hello everyone, my name is wangzirui32, today I will teach you how to use the urllib module to download files on the Internet.

1. Determine what to download

Here I chose the icon of the CSDN official website, the image link is https://img-home.csdnimg.cn/images/20201124032511.png , which is the following image:
image

2. Write the code

# 我们使用Python内置模块urllib来下载
from urllib.request import urlopen

# 图片url
url = "https://img-home.csdnimg.cn/images/20201124032511.png"

# 创建一个图片文件
# 注意:wb指以二进制的形式写入文件
with open("pic.png", "wb") as f:
	# urlopen(url)访问一个网址
	# read()读取数据
	# write()存储到文件中
    f.write(urlopen(url).read())

The above code realizes the function of automatically downloading files.
Of course, the url can be changed, and the name of the stored file can also be changed. If we want the file name on the network to be the same as the stored file name, we can write the code like this:

from urllib.request import urlopen

url = "https://img-home.csdnimg.cn/images/20201124032511.png"

# 重点:url.split("/")[-1]
with open(url.split("/")[-1], "wb") as f:
    f.write(urlopen(url).read())

First, we use the split function to separate the parts of the webpage with "/" and arrange them into a list. The last item of this list is the file name.


Okay, that's it for today's course. I hope you can learn a lot, bye!

Guess you like

Origin blog.csdn.net/wangzirui32/article/details/114228732