Python爬虫实现HTTP网络请求多种实现方式


Posted in Python onJune 19, 2020

1、通过urllib.requests模块实现发送请求并读取网页内容的简单示例如下:

#导入模块
import urllib.request
#打开需要爬取的网页
response = urllib.request.urlopen('http://www.baidu.com')
#读取网页代码
html = response.read()
#打印读取的内容
print(html)

结果:

b'<!DOCTYPE html><!--STATUS OK-->\n\n\n \n \n       <html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta content="always" name="referrer"><meta name="theme-color" content="#2932e1"><meta name="description" content="\xe5\x85\xa8\xe7\x90\x83\xe6\x9c\x80\xe5\xa4\xa7\xe7\x9a\x84\xe4\xb8\xad\xe6\x96\x87\xe6\x90\x9c\xe7\xb4\xa2\xe5\xbc\x95\xe6\x93\x8e\xe3\x80\x81\xe8\x87\xb4\xe5\x8a\x9b\xe4\xba\x8e\xe8\xae\xa9\xe7\xbd\x91\xe6\xb0\x91\xe6\x9b\xb4\xe4\xbe\xbf\xe6\x8d\xb7\xe5\x9c\xb0\xe8\x8e\xb7\xe5\x8f\x96\xe4\xbf\xa1\xe6\x81\xaf\xef\xbc\x8c\xe6\x89\xbe\xe5\x88\xb0\xe6\x89\x80\xe6\xb1\x82\xe3\x80\x82\xe7\x99\xbe\xe5\xba\xa6\xe8\xb6\x85\xe8\xbf\x87\xe5\x8d\x83\xe4\xba\xbf\xe7\x9a\x84\xe4\xb8\xad\xe6\x96\x87\xe7\xbd\x91\xe9\xa1\xb5\xe6\x95\xb0\xe6\x8d\xae\xe5\xba\x93\xef\xbc\x8c\xe5\x8f\xaf\xe4\xbb\xa5\xe7\x9e\xac\xe9\x97\xb4\xe6\x89\xbe\xe5\x88\xb0\xe7\x9b\xb8\xe5\x85\xb3\xe7\x9a\x84\xe6\x90\x9c\xe7\xb4\xa2\xe7\xbb\x93\xe6\x9e\x9c\xe3\x80\x82"><link rel="shortcut icon" href="/favicon.ico" rel="external nofollow" type="image/x-icon" /><link rel="search" type="application/opensearchdescription+xml" href="/content-search.xml" rel="external nofollow" title="\xe7\x99\xbe\xe5\xba\xa6\xe6\x90\x9c\xe7\xb4\xa2" /><link rel="icon" sizes="any" mask href="//www.baidu.com/img/baidu_85beaf5496f291521eb75ba38eacbd87.svg" rel="external nofollow" ><link rel="dns-prefetch" href="//dss0.bdstatic.com" rel="external nofollow" /><link rel="dns-prefetch" href="//dss1.bdstatic.com" rel="external nofollow" /><link rel="dns-prefetch" href="//ss1.bdstatic.com" rel="external nofollow" /><link rel="dns-prefetch" href="//sp0.baidu.com" rel="external nofollow" /><link rel="dns-prefetch" href="//sp1.baidu.com" rel="external nofollow" /><link rel="dns-prefetch" href="//sp2.baidu.com" rel="external nofollow" /><title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93</title><style index="newi" type="text/css">#form .bdsug{top:39px}.bdsug{display:none;position:absolute;width:535px;background:#fff;border:1px solid 
………………(太多省略)

以上示例中是通过get请求方式获取百度的网页内容。

下面是通过urllib.request模块的post请求实现获取网页信息的内容:

#导入模块
import urllib.parse
import urllib.request
#将数据使用urlencode编码处理后,再使用encoding设置为utf-8编码
data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')
#打开指定需要爬取的网页
response = urllib.request.urlopen('http://httpbin.org/post',data=data)
html = response.read()
#打印读取的内容
print(html)

结果:

b'{\n "args": {}, \n "data": "", \n "files": {}, \n "form": {\n "word": "hello"\n }, \n "headers": {\n "Accept-Encoding": "identity", \n "Content-Length": "10", \n "Content-Type": "application/x-www-form-urlencoded", \n "Host": "httpbin.org", \n "User-Agent": "Python-urllib/3.7", \n "X-Amzn-Trace-Id": "Root=1-5ec3f607-00f717e823a5c268fe0e0be8"\n }, \n "json": null, \n "origin": "123.139.39.71", \n "url": "http://httpbin.org/post"\n}\n'

2、urllib3模块

通过urllib3模块实现发送网络请求的示例代码:

#导入模块
import urllib3
#创建PoolManager对象,用于处理与线程池的连接以及线程安全的所有细节
http = urllib3.PoolManager()
#对需要爬取的网页发送请求
response = http.request('GET','https://www.baidu.com/')
#打印读取的内容
print(response.data)

结果:

b'<!DOCTYPE html><!--STATUS OK-->\r\n<html>\r\n<head>\r\n\t<meta http-equiv="content-type" content="text/html;charset=utf-8">\r\n\t<meta http-equiv="X-UA-Compatible" content="IE=Edge">\r\n\t<link rel="dns-prefetch" href="//s1.bdstatic.com" rel="external nofollow" />\r\n\t<link rel="dns-prefetch" href="//t1.baidu.com" rel="external nofollow" />\r\n\t<link rel="dns-prefetch" href="//t2.baidu.com" rel="external nofollow" />\r\n\t<link rel="dns-prefetch" href="//t3.baidu.com" rel="external nofollow" />\r\n\t<link rel="dns-prefetch" href="//t10.baidu.com" rel="external nofollow" />\r\n\t<link rel="dns-prefetch" href="//t11.baidu.com" rel="external nofollow" />\r\n\t<link rel="dns-prefetch" href="//t12.baidu.com" rel="external nofollow" />\r\n\t<link rel="dns-prefetch" href="//b1.bdstatic.com" rel="external nofollow" />\r\n\t<title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93</title>\r\n\t<link href="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/home/css/index.css" rel="external nofollow" rel="stylesheet" type="text/css" />\r\n\t<!--[if lte IE 8]><style index="index" >#content{height:480px\\9}#m{top:260px\\9}</style><![endif]-->\r\n\t<!--[if IE 8]><style index="index" >#u1 a.mnav,#u1 a.mnav:visited{font-family:simsun}</style><![endif]-->\r\n\t<script>var hashMatch = document.location.href.match(/#+(.*wd=[^&].+)/);if (hashMatch && hashMatch[0] && hashMatch[1]) {document.location.replace("http://"+location.host+"/s?"+hashMatch[1]);}
…………………………(太多省略)

post请求实现获取网页信息的内容:

#导入模块
import urllib3
#创建PoolManager对象,用于处理与线程池的连接以及线程安全的所有细节
http = urllib3.PoolManager()
#对需要爬取的网页发送请求
response = http.request('POST','http://httpbin.org/post',fields={'word':'hello'})
#打印读取的内容
print(response.data)

结果:

b'{\n "args": {}, \n "data": "", \n "files": {}, \n "form": {\n "word": "hello"\n }, \n "headers": {\n "Accept-Encoding": "identity", \n "Content-Length": "128", \n "Content-Type": "multipart/form-data; boundary=06ff68d7a4a22f600244a70bf9382ab2", \n "Host": "httpbin.org", \n "X-Amzn-Trace-Id": "Root=1-5ec3f8c3-9f33c46c1c1b37f6774b84f2"\n }, \n "json": null, \n "origin": "123.139.39.71", \n "url": "http://httpbin.org/post"\n}\n'

3、requests模块

以GET请求方式为例,打印多种请求信息的代码:

#导入模块
import requests
#对需要爬取的网页发送请求
response = requests.get('http://www.baidu.com')
#打印状态码
print('状态码:',response.status_code)
#打印请求url
print('url:',response.url)
#打印头部信息
print('header:',response.headers)
#打印cookie信息
print('cookie:',response.cookies)
#以文本形式打印网页源码
print('text:',response.text)
#以字节流形式打印网页源码
print('content:',response.content)

结果:

状态码: 200
url: http://www.baidu.com/
header: {'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Tue, 19 May 2020 15:28:30 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:27:32 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}
cookie: <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
text: <!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8>
………………(此处省略)
content: b'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8>
………………(此处省略)

以POST请求方式,发送HTTP网页请求的示例:

#导入模块
import requests
#表单参数
data = {'word':'hello'}
#对需要爬取的网页发送请求
response = requests.post('http://httpbin.org/post',data=data)
#以字节流形式打印网页源码
print(response.content)

结果:

b'{\n "args": {}, \n "data": "", \n "files": {}, \n "form": {\n "word": "hello"\n }, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Content-Length": "10", \n "Content-Type": "application/x-www-form-urlencoded", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.23.0", \n "X-Amzn-Trace-Id": "Root=1-5ec3fc97-965139d919e5a08e8135e731"\n }, \n "json": null, \n "origin": "123.139.39.71", \n "url": "http://httpbin.org/post"\n}\n'

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python对两个有序列表进行合并和排序的例子
Jun 13 Python
Python读取图片属性信息的实现方法
Sep 11 Python
Python数据持久化shelve模块用法分析
Jun 29 Python
使用django的ORM框架按月统计近一年内的数据方法
Jul 18 Python
使用turtle绘制五角星、分形树
Oct 06 Python
Flask框架请求钩子与request请求对象用法实例分析
Nov 07 Python
python操作docx写入内容,并控制文本的字体颜色
Feb 13 Python
解决pycharm中opencv-python导入cv2后无法自动补全的问题(不用作任何文件上的修改)
Mar 05 Python
在python中利用pycharm自定义代码块教程(三步搞定)
Apr 15 Python
Python操作Word批量生成合同的实现示例
Aug 28 Python
python 绘制场景热力图的示例
Sep 23 Python
next在python中返回迭代器的实例方法
Dec 15 Python
Keras设置以及获取权重的实现
Jun 19 #Python
Python包和模块的分发详细介绍
Jun 19 #Python
浅谈Keras中shuffle和validation_split的顺序
Jun 19 #Python
Python爬虫headers处理及网络超时问题解决方案
Jun 19 #Python
sklearn和keras的数据切分与交叉验证的实例详解
Jun 19 #Python
Python虚拟环境的创建和包下载过程分析
Jun 19 #Python
通过实例解析python创建进程常用方法
Jun 19 #Python
You might like
MySQL相关说明
2007/01/15 PHP
PHP程序漏洞产生的原因分析与防范方法说明
2014/03/06 PHP
Yii1.1框架实现PHP极光推送消息通知功能
2018/09/06 PHP
用JavaScript页面不刷新时全选择,全删除(GridView)
2009/04/14 Javascript
Jquery 组合form元素为json格式,asp.net反序列化
2009/07/09 Javascript
jQuery 使用手册(二)
2009/09/23 Javascript
19个很有用的 JavaScript库推荐
2011/06/27 Javascript
探讨javascript是不是面向对象的语言
2013/11/21 Javascript
jquery 实现两级导航菜单附效果图
2014/03/07 Javascript
JavaScript实现计算字符串中出现次数最多的字符和出现的次数
2015/03/12 Javascript
jquery实现键盘左右翻页特效
2015/04/30 Javascript
jQuery实现Flash效果上下翻动的中英文导航菜单代码
2015/09/22 Javascript
JavaScript实现获取某个元素相邻兄弟节点的prev与next方法
2016/01/25 Javascript
深入剖析JavaScript面向对象编程
2016/07/12 Javascript
浅谈jQuery的bind和unbind事件(绑定和解绑事件)
2017/03/02 Javascript
jquery中$.fn和图片滚动效果实现的必备知识总结
2017/04/21 jQuery
Angular 4 指令快速入门教程
2017/06/07 Javascript
如何更好的编写js async函数
2018/05/13 Javascript
详解vue-cli脚手架中webpack配置方法
2018/08/22 Javascript
微信小程序Flex布局用法深入浅出分析
2019/04/25 Javascript
微信小程序登录对接Django后端实现JWT方式验证登录详解
2019/07/29 Javascript
Vue中computed和watch有哪些区别
2020/12/19 Vue.js
[55:44]OG vs NAVI 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
python基于BeautifulSoup实现抓取网页指定内容的方法
2015/07/09 Python
python ddt实现数据驱动
2018/03/14 Python
django中模板的html自动转意方法
2018/05/27 Python
django解决跨域请求的问题
2018/11/11 Python
Python检测端口IP字符串是否合法
2020/06/05 Python
Html5 canvas实现粒子时钟的示例代码
2018/09/06 HTML / CSS
HTML5调用手机发短信和打电话功能
2020/04/29 HTML / CSS
基本公共卫生服务健康教育工作方案
2014/05/22 职场文书
客房服务员岗位职责
2015/02/09 职场文书
趣味运动会简讯
2015/07/20 职场文书
我爱我班主题班会
2015/08/13 职场文书
python基于tkinter制作下班倒计时工具
2021/04/28 Python
关于PHP数组迭代器的使用方法实例
2021/11/17 PHP