爬虫练习-urllib的使用2

117 阅读1分钟
#请求对象的定制
#url的组成
#1。协议  http/https(加密)
#2。主机(域名)
#3。端口号  http(80)/https(443)  mysql(3306) /orical(1521)/redis(6379)/mongodb(27017)
#4 路径
#5.参数
#6 锚点
import urllib.request

url='http://www.baidu.com'

headers={ 
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'
}
#urlopen方法中不能存储字典,所以headers不能传递进去
#请求对象的定制
#注意 因参数顺序的问题  不能直接传参  中间还有一个data  所以需要关键字传参
request=urllib.request.Request(url=url,headers=headers)
response=urllib.request.urlopen(request)
contennt=response.read().decode('utf-8')
print(contennt)
#get请求 quote方法
import  urllib.request
import urllib.parse

# url='https://www.bilibili.com/read/cv17800891?from=category_0'

url='http://www.baidu.com/s?wd='

#请求对象的定制  是解决反爬的第一中手段
headers={
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'
}

#将汉字转unicode编码
name=urllib.parse.quote('周杰伦')
print(f"{name}")
url=url+name

#请求对象定制
request=urllib.request.Request(url=url,headers=headers)

#模拟浏览器向服务器发送请求
response=urllib.request.urlopen(request)

#获取响应内容
content=response.read().decode('utf-8')

print(content)
#请求百度翻译
import  urllib.request
import  urllib.parse
import  json

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

headers={
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'
}

data={
    'kw':'spider'
}

#post 请求的参数  必须要进行编码

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

#post 请求的参数需要进行编码
requests=urllib.request.Request(url=url,data=data,headers=headers)
print(requests)

response=urllib.request.urlopen(requests)

content=response.read().decode('utf-8')

print(content)

#字符串转json对象
obj=json.loads(content)
print(obj)