欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python爬虫——Request之get请求和post请求

程序员文章站 2024-01-19 11:10:58
...

Get请求: 

#引用模块
import  urllib.request as ur
#创建Request对象
request = ur.Request('https://edu.csdn.net/')
#读取
response = ur.urlopen(request).read()
print(response)

python爬虫——Request之get请求和post请求 

#粘贴过来的百度贴吧英雄联盟吧
#url='https://tieba.baidu.com/f?kw=%E8%8B%B1%E9%9B%84%E8%81%94%E7%9B%9F&ie=utf-8&pn=0'
#解码#
import urllib.parse as up
import urllib.request as ur

#kw='英雄联盟'
kw='美剧'
data = {
    'kw': kw,
    'ie': 'utf-8',
    'pn': '100'
}
#编码
data_url = up.urlencode(data)
#print(data_url)
#解码
ret = up.unquote(data_url)
#根据解码对象生成连接
request = ur.Request('https://tieba.baidu.com/f?'+data_url)
#读取
response = ur.urlopen(request).read()
with open('%s.html'% kw ,'wb') as f:
    f.write(response)
print(response)

Post请求:做一个百度翻译:

python爬虫——Request之get请求和post请求

python爬虫——Request之get请求和post请求

python爬虫——Request之get请求和post请求 

import urllib.request as ur
import urllib.parse as up
import json

word= input('请输入要翻译的英语:')

data={
    'kw':word
}

data_url = up.urlencode(data)

request = ur.Request(url='https://fanyi.baidu.com/sug',data=data_url.encode('utf-8'))
reponse = ur.urlopen(request).read()

ret = json.loads(reponse)
#print(ret)

translate = ret['data'][0]['v']
print(translate)

 

相关标签: Django 爬虫