爬虫学习(二)

爬取html
import urllib.request

# 请求行
url = "http://www.baidu.com"

# 专门处理url进行数据的读取
response = urllib.request.urlopen(url)

# 以二进制的方式进行数据的读取
# print(response.read().decode("UTF8"))

# 得到的是响应的头部信息
print(response.headers)

# 得到响应头,返回的是一个含有头信息的元祖的列表
print(response.getheaders())

#获取响应码

print(response.getcode())

# 将响应的数据保存到文件中
# 第一种方式
with open("baidu.html","w",encoding="utf8")as fp:
fp.write(response.read().decode("utf8"))

#第二种方式
url = "http://www.baidu.com/"

#urlretrieve()是指直接读取url并将读取的文件写入到指定的文件中

urllib.request.urlretrieve(url,"baidu3.html")


爬去网页上的图片

先指定图片的网址,注意网址必须是以图片的格式结尾

imgurl="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike116%2C5%2C5%2C116%2C38/sign=f95f755efa36afc31a013737d27080a1/8ad4b31c8701a18b7dc62ad1932f07082838fe7b.jpg"

读取图片的数据

response1 = urllib.request.urlopen(imgurl)

并将图片按照图片的格式显示出来

with open("wu.png","wb") as tf:

      tf.write(response1.read())

 

 

posted @ 2019-02-12 10:43  石桥浪子  阅读(253)  评论(0编辑  收藏  举报