美文网首页python 爬虫
2020-02-01 python 爬虫小练习-下载“百度”图片

2020-02-01 python 爬虫小练习-下载“百度”图片

作者: 可乐W | 来源:发表于2020-02-07 15:48 被阅读0次

1.python 爬虫小练习

#爬虫

import requests#第三方库

url="http://www.baidu.com"

response =requests.get(url)#下载

html = response.text

print(html)

2.python 爬虫小练习-下载“百度”图片

 我想把百度首页的上面的百度图标下载下来应该怎么办呢,接下来进行学习。

一.网页的操作
首先需要进行知道这个图标的地址:

#方法1(不用函数):

import requests

#图片的url

 img_url="http://www.baidu.com/img/pc_1c6e30772d5e4103103bd460913332f9.png" #注:地址要搞清楚,很重要。

#下载图片

 response = requests.get(img_url)

# 取出数据,写文件

# 图片数据

 img_data = response.content

 with open("baidu.png", "wb") as f:  # 文件操作 打开文件 -保存的文件名,文件的形式 -文件写入f.write

  f.write(img_data)

方法2(定义函数):

import requests

#下载百度图片

#右击-查看元素-看到源代码-找到img的src-新建标签-复制url

#图片的url

def download_img(img_url,file_name):

    response = requests.get(img_url)

# 取出数据,写文件

# 图片数据

    img_data =response.content

    with open(file_name,"wb")as f:#文件操作 打开文件 -保存的文件名,文件的形式 -文件写入f.write

        f.write(img_data)

download_img("http://www.baidu.com/img/pc_1c6e30772d5e4103103bd460913332f9.png","baidu.png")

结果:

结果就是在左边栏里会出现一个baidu.png,然后可以打开。

相关文章

网友评论

    本文标题:2020-02-01 python 爬虫小练习-下载“百度”图片

    本文链接:https://www.haomeiwen.com/subject/dyqxxhtx.html