爬虫之urllib库使用

请求方法request

import urllib.request
url = "https://blog.csdn.net/fengxinlinux/article/details/77281253"
# 打开网页,读取所有内容,注意read出来的是bytes类型的数据
respons = request.urlopen(url=url).read()
# 数据持久化,将读取出来的数据保存在本地
with open("./csdn.html","wb") as fp:
    fp.write(respons)
    print("数据下载成功")

编码parse中的quote方式

import urllib.request
import urllib.parse
# 用户输入搜索的关键字
choice = input("请输入您要查询的关键字>>>:").strip()
# 对关键字进行编码,url不可以出现非ASCII编码的字符数据
Keyword = urllib.parse.quote(choice)
# 将编码后的搜索条件拼接到url上
url = "http://www.baidu.com/s?wd={}".format(Keyword)
# 请求网址
response = urllib.request.urlopen(url=url)
# read取出相应数据,读取出来的是bytes类型的数据
html = response.read()
# 数据持久化,保存到本地
with open("./关键字搜索.html","wb")as fp:
    fp.write(html)
    print("下载完成")

UA伪装

import urllib.request
import urllib.parse
# 用户输入搜索的关键字
choice = input("请输入您要查询的关键字>>>:").strip()
# 对关键字进行编码,url不可以出现非ASCII编码的字符数据
Keyword = urllib.parse.quote(choice)
# 将编码后的搜索条件拼接到url上
url = "https://www.baidu.com/s?wd={}".format(Keyword)
# 伪装浏览器
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}
# 自定制请求对象,加入请求头
request_obj = urllib.request.Request(url=url,headers=header)
# 对我们自定制的请求对象发起请求
response = urllib.request.urlopen(request_obj)
# read取出相应数据,读取出来的是bytes类型的数据
print(response.read())

POST请求

Ajax请求

抓取百度翻译结果

# post请求
# 抓取百度翻译的翻译结果
# 百度翻译基于Ajax发起的请求
import urllib.request
import urllib.parse
import json
# 用户输入要翻译的关键字
choice = input("请输入您要翻译的关键字>>>:").strip()
# 在网页中用开发者工具找到Ajax请求的真实网址
url = "https://fanyi.baidu.com/sug"
# 构建请求参数
data = {
    'kw':choice,
}
# 对参数进行编码处理,返回值为str,kw=%E5%93%88
data = urllib.parse.urlencode(data)
# 将编码后的结果转换成bytes类型
data = data.encode()
# 发起post请求,经过处理后的data就是post请求携带的参数,返回值为bytes类型
response = urllib.request.urlopen(url=url,data=data)
# 将bytes解码
json.loads(response.read())

 

posted @ 2019-07-08 21:40  叫我大表哥  阅读(361)  评论(0编辑  收藏  举报