程序员超体数据库,创建爬虫。

无私分享全套Python爬虫干货,如果你也想学习Python,@ 私信小编获取

在网页浏览中,网络浏览器是一个非常有用的应用,它创建信息的数据包,发送它们,然后把你获取的数据解释成漂亮的图像、声音、视频和文字。但是,网络浏览器就是代码,而代码是可以分解的,可以分解成许多基本组件,可重写、重用,以及做成我们想要的任何东西。网络浏览器可以让服务器发送一些数据,到那些对接无线(或有线)网络接口的应用上,但是python也有实现这些功能的文件库。

下面是python实现浏览器的代码

<code>from urllib.request import urlopen
html=urlopen("http://pythonscraping.com/pages/page1.html")
print(html.read())/<code>

requests库

Requests是用Python语言编写的,基于urllib3来改写的,采用Apache2 Licensed 来源协议的HTTP库。它比urllib更加方便,可以节约我们大量的工作,完全满足HTTP测试需求。在日常使用中我们绝大部分使用requests库向目标网站发起HTTP请求。

urllib 库中的urlopen()方法实际上是以GET方式请求网页,而requests 中相应的方法就是get()。在Python中运行以下代码:

<code>mport requests
# 以get方式获取百度官网源代码
res = requests.get("https://www.baidu.com")

# 获取返回类型
print(type(res))
# 获取状态码
print(res.status_code)
# 获取返回源代码内容类型
print(type(res.text))
# 获取前15字符
print((res.text)[:15])
# 获取cookies
print(res.cookies)/<code>

输出结果为:

<code><class>
200 # 状态码200代表响应正常
<class>

<requestscookiejar>/<class>/<class>/<code>

get方法是我们通常最常用的方法。输入如下代码对网站提交get请求:

<code>import requests
res = requests.get("http://httpbin.org/get")
print(res.text)/<code>

输出结果为:

<code>{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.22.0",
"X-Amzn-Trace-Id": "Root=1-5e5dd355-96131363cf818957b8e7b67d"
},
"origin": "171.112.101.74",
"url": "http://httpbin.org/get"
}/<code>

由上述输出可知响应结果包含请求头、URL和IP等信息。而如果我们想在get请求中输入参数信息,则需要设置params参数:

<code>​import requests
data = {
'building':"zhongyuan",
'nature':"administrative"
}
res = requests.get("http://httpbin.org/get",params=data)
print(res.text)
/<code>

输出内容为:

<code>{
"args": {
"building": "zhongyuan",
"nature": "administrative"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.22.0",
"X-Amzn-Trace-Id": "Root=1-5e5dd4db-f0568e98f3350cae8998968a"
},
"origin": "171.112.101.74",
"url": "http://httpbin.org/get?building=zhongyuan&nature=administrative"/<code>

为了帮助大家更轻松的学好Python,我给大家分享一套Python学习资料,希望对正在学习的你有所帮助!

获取方式:关注并私信小编 “ 学习 ”,即可免费获取!


程序员超体数据库,创建爬虫。


分享到:


相關文章: