LOADING

加载过慢请开启缓存 浏览器默认开启

千百度's space

——a tree hole for nichijou

我们所度过的每一个日常,或许就是连续不断发生的奇迹

urllib库(8)handler处理器

2023/11/6
#用handler来访问百度
import urllib.request


url = 'http://www.baidu.com'
headers = {
'User-Agent':
'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36 Edg/118.0.2088.46'
}

request = urllib.request.Request(url=url,headers=headers)
#(1)获取handler对象
handler = urllib.request.HTTPHandler()
#(2)获取opener对象
opener = urllib.request.build_opener(handler)
#(3)调用opener对象
response = opener.open(request)
content = response.read().decode('utf-8')
print(content)
阅读全文

urllib库(8)代理和代理池

2023/11/6

代理和代理池

一个伪装的ip地址,用一个字典表示
例:

proxies = {
    'http':'118.24.219.151:16817'
}

代理池就是多个代理组成的字典
例:

proxies_pool = [
    {'http':'118.24.219.151:16817'},
    {'http':'113.124.93.38:9999'}
]

代理的使用语法

request = urllib.request.Request(url=url,headers=headers)
handler = urllib.request.ProxyHandler(proxies=proxies)
opener = urllib.request.build_opener(handler)
response = opener.open(request)

从代理池中随机抽取一个代理:

import random
proxies = random.choice(proxies_pool)
阅读全文

urllib库(7)异常

2023/11/6

常出现的两种异常:

1、HTTPError:出现在url种某个字符出现问题的时候
2、URLError:出现在这个url不存在的时候
其中:HTTPError是URLError的一个子类

示例:

import urllib.request
import urllib.error
url1 = 'https://blog.csdn.net/boysoft2002/article/details/132520234'
url2 = 'https://blog.csdn.net/boy__soft2002/article/details/132520234'#HTTPError
url3 = 'http://www.yangkeyu.com'#URLError



headers = {
'Accept':
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'User-Agent':
'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36 Edg/118.0.2088.46'
}


try:
    request = urllib.request.Request(url=url3, headers=headers)
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    print(content)
except urllib.error.HTTPError:
    print('出现http错误')
except urllib.error.URLError:
    print("出现了url错误")
阅读全文

urllib库(6)ajax

2023/11/6

什么是ajax?

含有多个多个页面时,常有ajax请求,ajax请求也分为ajax的post请求和ajax的get请求

如何判断运用了ajax请求?

当headers中出现:X-Requested-With: XMLHttpRequest时,说明就是一个ajax请求

代码示例:获得豆瓣电影前20页的数据

import urllib.request
import urllib.parse
url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'

def create_request(page):
    base_url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'
    data = {
        'cname': '上海',
        'pid':'',
        'pageIndex': page,
        'pageSize': 10
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36 Edg/118.0.2088.46',
        'Accept': '*/*',
        'Cookie': 'll="108296"; bid=DIZJHJYe40Y; _pk_ref.100001.4cf6=%5B%22%22%2C%22%22%2C1697503350%2C%22https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3D7mX7_DYj1rvpVbk1-XVpnHlGWhhuOHcRgjFNbC0KoWEMe4-wytQfL4FZvJtRsTxC%26wd%3D%26eqid%3De80b52bb0000c24600000005652dd873%22%5D; _pk_ses.100001.4cf6=1; ap_v=0,6.0; __yadk_uid=cSeoVvLDVBPux8QedPv8ZhjqjQMyW7Ka; _vwo_uuid_v2=D0271D0AFA2BFE022D7B32A84C9C79BA9|9f33d547e5bc95d46eac63303551a3cb; _pk_id.100001.4cf6=3c8e0eace73a58d7.1697503374.; Hm_lvt_16a14f3002af32bf3a75dfe352478639=1697503401; Hm_lpvt_16a14f3002af32bf3a75dfe352478639=1697503401; __utma=30149280.267631944.1656475391.1656491114.1697503809.3; __utmb=30149280.0.10.1697503809; __utmc=30149280; __utmz=30149280.1697503809.3.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=223695111.902583869.1656491114.1656491114.1697503809.2; __utmb=223695111.0.10.1697503809; __utmc=223695111; __utmz=223695111.1697503809.2.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)'
    }

    data = urllib.parse.urlencode(data).encode('utf-8')
    request = urllib.request.Request(url=base_url,data=data,headers=headers)
    return request

def get_content(request):
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    return content


def download(content,page):
    with open('kfc'+str(page)+'.json','w',encoding='utf-8') as file_object:
        file_object.write(content)
if __name__ == '__main__':
    start_page = int(input('请输入起始页码: '))
    end_page = int(input('请输入终止页码: '))
    for page in range(start_page,end_page+1):
        request = create_request(page)
        content = get_content(request)
        download(content,page)
阅读全文

urllib库(4)请求对象的定制

2023/11/6

一个url的组成

示例:https://www.baidu.com/s?wd=%E5%91%A8%E6%9D%B0%E4%BC%A6&sex=%E7%94%B7&location=%E4%B8%AD%E5%9B%BD%E5%8F%B0%E6%B9%BE%E7%9C%81
1、协议:http/https
2、主机:www.baidu.com
3、端口号:
http:80
https:443
mysql:3306
oracle:1521
redis:6379
mongodb:27107
4、路径:s
5、参数:问号之后的数据
6、锚点

http和https协议的区别

https经过加密,如果直接用urlopen函数打开使用https协议的url,那么获取到的数据就是不完整的

用户代理

User-Agent:一个反爬虫,放在一个名为headers的字典中

headers包含了很多参数,例如Accept,Cookie等,但是最重要的参数还是Cookie!

请求对象的定制

函数urlopen的传参URL可以是一个字符串表示的url,也可以是一个request类型的对象

把url和headers传入,获得一个request类型的对象,然后再传入urlopen函数中去获得响应

特别注意:这里定制request对象必须用关键字传参!因为url和headers中间还有一个data传参,因此不能使用顺序传参!

import urllib.request
url = "https://www.baidu.com"


headers = {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36'
}


request = urllib.request.Request(url = url,headers = headers)

response = urllib.request.urlopen(request)
content = response.read().decode("utf-8")
print(content)
阅读全文

urllib库(4)——post请求

2023/11/6

关于请求的方式

不同网页的请求方式不同,请求方式需要在网页打开后台来查询

post请求的特点

1、post请求的参数,必须要事先用urlencode编码,urlencode会把字典变成Unicode编码,这时要再用encode('utf-8)把Unicode码变成byte!
2、post请求的参数需要放在一个列表中,在生成request对象的时候,作为data参数传入
3、获取到网页的源码后,记得要反序列化后才能阅读。

#post请求
import urllib.request
import urllib.parse
import json
url = 'https://fanyi.baidu.com/sug' #在原网页中,可以看出url的请求方式是post
headers = {
'Accept':
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'User-Agent':
'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36 Edg/118.0.2088.46'
}

data={
    'kw':'spider'
}


data = urllib.parse.urlencode(data).encode('utf-8')


request = urllib.request.Request(url=url,data=data,headers=headers)
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')

print(content)
print(type(content))
#反序列化,把字符串变成字典
obj = json.loads(content)
print(obj)
print(type(obj))
阅读全文

urllib库(3)——下载

2023/11/6

下载需要文件名和url

import urllib.request

#下载网页
url_page = "http://www.baidu.com"
#url代表的是下载的路径,file_name代表表的是文件名
#urllib.request.urlretrieve(url_page, 'baidu.html')

#下载图片
url_image = 'https://img1.baidu.com/it/u=36041914,4185692496&fm=253&fmt=auto&app=138&f=JPEG?w=270&h=180'
urllib.request.urlretrieve(url_image,'孤独摇滚.jpg')

#下载视频
阅读全文

urllib库(2)——编码

2023/11/6

如今最常用的编码方式是unicode编码,Unicode编码可以把文字编码后夹在url后作为后缀

quote编码

#如今的常用编码方式:unicode编码
import urllib.parse
import urllib.request
import time

url = 'https://www.baidu.com/s?w='

headers={
'User-Agent':
'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36 Edg/118.0.2088.46',
'Accept':
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'


}

#把汉字变成Unicode编码模式:编码
name=urllib.parse.quote("葬送的芙莉莲")
url=url+name
print(url)
request = urllib.request.Request(url=url, headers=headers)
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')

print(content)

用urlencode方式编码

#如今的常用编码方式:unicode编码
import urllib.parse
import urllib.request
import time

url = 'https://www.baidu.com/s?w='

headers={
'User-Agent':
'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36 Edg/118.0.2088.46',
'Accept':
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'


}

#把汉字变成Unicode编码模式:编码
name=urllib.parse.quote("葬送的芙莉莲")
url=url+name
print(url)
request = urllib.request.Request(url=url, headers=headers)
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')

print(content)

总结:
quote编码适用于只需要编码一个对象的时候,其传入的参数是一个字符串
urlencode编码适用于要编码多个对象的时候,其传入的参数是一个列表

阅读全文

urllib库(1)——基本用法

2023/11/6

使用urllib获取网页数据的基本流程

1、定义一个url
2、模拟浏览器向服务器发送请求
3、获取相应页面的源码
4、把源码解码

#使用urllib来获取百度页面的原数据

import urllib.request
#1、定义一个url
url = 'http://www.baidu.com'
#2、模拟浏览器向服务器发送请求
response = urllib.request.urlopen(url)
#3、获取相应中的页面的源码
#read返回的是字节形式的二进制数据
#将二进制数据转换为字符串:解码
#解码:decode('编码的格式')
content = response.read().decode('utf-8')

print(content)

urllib的一个类型和6种方法

一个类型

response是HTTPResponse的类型

6种方法

1、一个一个字节来读
2、n个n个字节来读
3、只读一行
4、一行一行来读直到读完
5、返回url地址
6、返回网页的状态

附加方法:检查response是否有逻辑错误

实例代码:

import urllib.request
url = "http://www.baidu.com"
response = urllib.request.urlopen(url)
#一个类型和六个方法
#print(type(response))
#response是HTTPResponse的类型

#按照一个一个字节来读
"""content = response.read()
print(content)"""

#read(n)表示返回n个字节
"""content = response.read(5)
print(content)"""

#读取一行
"""content = response.readline()
print(content)"""

#一行一行来读直到读完
"""content = response.readlines()
print(content)"""

#返回状态码 如果是200 则说明逻辑没有错误
#print(response.getcode())

#返回url地址
#print(response.geturl())

#获取的是一些状态信息
print(response.getheaders())
阅读全文

序列化和反序列化

2023/11/6

序列化

把列表、字典等类型的对象转换为字符串类型之后才可以写进txt文件中

有dumps和dump两种用法:

import json
#dumps
"""
with open('example.txt','w') as object:
    a = ['yes', 'no']
    b = json.dumps(a)
    #此时b的类型是str
    object.write(b)
"""
#dump
#在将字符串转换为对象的同时,指定一个文件的对象,然后把转换后的字符串写进这个文件里

with open("example.txt",'w',encoding='utf-8') as object:
    a = ['yes', 'no','yes']
    json.dump(a, object)
    print(object)

反序列化

把txt文件中的str字符串还原成python中的各类对象

有load和loads两种用法

import json
#dumps
"""
with open('example.txt','w') as object:
    a = ['yes', 'no']
    b = json.dumps(a)
    #此时b的类型是str
    object.write(b)
"""
#dump
#在将字符串转换为对象的同时,指定一个文件的对象,然后把转换后的字符串写进这个文件里

with open("example.txt",'w',encoding='utf-8') as object:
    a = ['yes', 'no','yes']
    json.dump(a, object)
    print(object)
阅读全文
1 ... 2 3
avatar
千百度

Stay hungry, stay foolish.