爬虫学习(1)

小白整理大一期间学习的爬虫知识

在学习爬虫前,我是学习了基础的python语法
对学过任何一门编程语言的人来说,还是比较容易上手的
并且需要有http协议等基础的知识

python3提供了原生的模块:urlib.request:

  1. urlopen:返回response对象,response.read(),bytes.decode("utf-8)
  2. get:传参(汉字报错:解释器ascii没有汉字,url汉字转码)
  3. post
  4. handle处理器的自定义
  5. urlError
  6. request(第三方)
  7. 数据解析:xpath bs4
  8. 数据存储

提供两个简单例子,跟一个老师学习的,注释都很详细

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","wb+")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()
import urllib.request
import urllib.parse
import string

def get_method_params():

    url = "http://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd="
    #拼接字符串(汉字)
    #python可以接受的数据
    #https://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)
    #UnicodeEncodeError: 'ascii' codec can't encode
    # characters in position 10-11: ordinal not in range(128)
    #python:是解释性语言;解析器只支持 ascii 0 - 127
    #不支持中文

get_method_params()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值