1.01-url-open_code

本文介绍了一个简单的Python程序,用于从指定URL(例如百度首页)抓取网页内容,并将其保存为本地HTML文件。程序使用了urllib.request模块进行HTTP请求及响应处理。
import urllib.request

def load_data():
    url = "http://www.baidu.com/"
    #get的请求
    #http请求
    #response:http相应的对象
    response = urllib.request.urlopen(url)
    print(response)
    #读取内容 bytes类型
    data = response.read()
    print(data)
    #将文件获取的内容转换成字符串
    str_data = data.decode("utf-8")
    print(str_data)
    #将数据写入文件
    with open("baidu.html","w",encoding="utf-8")as f:
        f.write(data)
    #将字符串类型转换成bytes
    str_name = "baidu"
    bytes_name =str_name.encode("utf-8")
    print(bytes_name)

    #python爬取的类型:str bytes
    #如果爬取回来的是bytes类型:但是你写入的时候需要字符串 decode("utf-8")
    #如果爬取过来的是str类型:但你要写入的是bytes类型 encode(""utf-8")
load_data()

转载于:https://www.cnblogs.com/hankleo/p/10591173.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值