Python-爬虫-拼接字符串

270 阅读1分钟
import urllib.request
import urllib.parse             # 转译使用模块
import string                   # 转译使用模块

def get_method_params():

    url = "http://www.baidu.com/s?ie=utf-8&wd="
    print(url)
    #拼接字符串(汉字)
    #python可以接受的数据
    #http://www.baidu.com/s?wd=%E7%BE%8E%E5%A5%B3

    name = "美女"
    final_url = url+name
    print(final_url)
    #代码发送了请求
    #网址里面包含了汉字;ASCII没有汉字;url转译
    #将包含汉字的网址进行转译
    encode_new_url = urllib.parse.quote(final_url,safe=string.printable)
    print(encode_new_url)
    response = urllib.request.urlopen(encode_new_url)
    print(response)
    #读取内容
    data = response.read().decode()
    print(data)
    #保存到本地
    with open("02-encode.html", "w", encoding="utf-8")as f:
        f.write(data)
get_method_params()

结果为: