爬虫的编解码方式

get请求的quote方法

我们在对爬取一个网页的时候,我们复制了这个网页的地址,但我们发现在将他粘贴下来以后不会是汉字,而是一串字符,这时候,我们需要去对字符进行编码,以便于我们能够继续去爬取网页。

例如我们要爬取周杰伦主页的网址:

首先我们需要去在浏览器搜索周杰伦

爬虫的编解码方式_第1张图片

 

 我们可以看到源码是带有汉字的,然后我们在进行爬取的时候会出现字符,这时候我们就需要去进行编码

#需求 获取https://www.baidu.com/s?wd=周杰伦的网页源码
#导入包
import urllib.request
import urllib.parse
定义url
url = 'https://www.baidu.com/s?wd='
headers = {
    "User-Agent":   'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.82'
}
#将周杰伦三个字变成unicode编码
name = urllib.parse.quote('周杰伦')
#拼接url
url = url+name
#定义请求对象
request = urllib.request.Request(url=url,headers = headers)
#模拟浏览器发送请求
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')
print(content)

 爬虫的编解码方式_第2张图片

 我们在获取user_Agent的时候对页面进行检查就可以获取了。

爬虫的编解码方式_第3张图片

 get请求的urlencode方法

在利用urlencode方法的时候,我们需要定义一个字典存储信息

import urllib.request
import urllib.parse
base_url = 'https://www.baidu.com/s?'
data = {
    'wd':'周杰伦',
    'sex':'男',
    'location':'中国台湾省'
}
new_data = urllib.parse.urlencode(data)
print(new_data)
url = base_url+new_data
headers = {
    "User-Agent":   'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.82'
}
#请求对象定制
request = urllib.request.Request(url=url,headers=headers)
#模拟浏览器发送请求
response = urllib.request.urlopen(request)
#获取网页端的数据
content=response.read().decode('utf-8')
print(content)

爬虫的编解码方式_第4张图片

 爬虫的post请求百度翻译

import urllib.request
import urllib.parse

url = 'https://fanyi.baidu.com/sug'


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


data = {
    'kw':'spider'
}
#post请求的参数一定要编码
data = urllib.parse.urlencode(data).encode('utf-8')
#post的请求参数不会拼接在url后面,需要放在请求对象的定制中
request = urllib.request.Request(url =url,data=data,headers=headers)
#模拟浏览器发送请求
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')
import json
obj = json.loads(content)

print(obj)

 这是最近学习的一些东西,简单记录一下。

你可能感兴趣的:(爬虫,python,开发语言)