爬虫开发python工具包介绍 (4)
本文来自网易云社区
作者:王涛
此处我们给出几个常用的代码例子,包括get,post(json,表单),带证书访问:
Get 请求
@gen.coroutine
def fetch_url():
try:
c = CurlAsyncHTTPClient() # 定义一个httpclient
myheaders = {
"Host": "weixin.sogou.com",
"Connection": "keep-alive",
"Cache-Control": "max-age=0",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.0 Safari/532.5 ",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8"
}
url = "http://weixin.sogou.com/weixin?type=1&s_from=input&query=%E4%BA%BA%E6%B0%91%E6%97%A5%E6%8A%A5&ie=utf8&_sug_=n&_sug_type_=" req = HTTPRequest(url=url, method="GET", headers=myheaders, follow_redirects=True, request_timeout=20, connect_timeout=10,
proxy_host="127.0.0.1",
proxy_port=8888)
response = yield c.fetch(req) # 发起请求
print response.code
print response.body
IOLoop.current().stop() # 停止ioloop线程
except:
print traceback.format_exc()
Fiddler 抓到的报文请求头:
POST JSON数据请求
@gen.coroutine
def fetch_url():
"""抓取url"""
try:
c = CurlAsyncHTTPClient() # 定义一个httpclient
myheaders = {
"Host": "weixin.sogou.com",
"Connection": "keep-alive",
"Cache-Control": "max-age=0",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.0 Safari/532.5 ",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
"Content-Type": "Application/json",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8"
}
url = "http://127.0.0.1?type=1&s_from=input&query=%E4%BA%BA%E6%B0%91%E6%97%A5%E6%8A%A5&ie=utf8&_sug_=n&_sug_type_="
body =json.dumps({"key1": "value1", "key2": "value2"}) # Json格式数据 req = HTTPRequest(url=url, method="POST", headers=myheaders, follow_redirects=True, request_timeout=20, connect_timeout=10,
proxy_host="127.0.0.1",proxy_port=8888,body=body)
response = yield c.fetch(req) # 发起请求
print response.code
print response.body
IOLoop.current().stop() # 停止ioloop线程
except:
print traceback.format_exc()
Fiddler 抓到的报文请求头:
POST Form表单数据请求
@gen.coroutine
def fetch_url():
"""抓取url"""
try:
c = CurlAsyncHTTPClient() # 定义一个httpclient
myheaders = {
"Host": "weixin.sogou.com",
"Connection": "keep-alive",
"Cache-Control": "max-age=0",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.0 Safari/532.5 ",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
# "Content-Type": "Application/json",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8"
}
import urllib
url = "http://127.0.0.1?type=1&s_from=input&query=%E4%BA%BA%E6%B0%91%E6%97%A5%E6%8A%A5&ie=utf8&_sug_=n&_sug_type_="
body =urllib.urlencode({"key1": "value1", "key2": "value2"}) # 封装form表单 req = HTTPRequest(url=url, method="POST", headers=myheaders, follow_redirects=True, request_timeout=20, connect_timeout=10,
proxy_host="127.0.0.1",proxy_port=8888,body=body)
response = yield c.fetch(req) # 发起请求
print response.code
print response.body
IOLoop.current().stop() # 停止ioloop线程
except:
print traceback.format_exc()
Fiddler 抓到的报文请求头:
添加证书访问
def fetch_url():
"""抓取url"""
try:
c = CurlAsyncHTTPClient() # 定义一个httpclient
myheaders = {
"Host": "www.amazon.com",
"Connection": "keep-alive",
"Cache-Control": "max-age=0",
"Upgrade-Insecure-Requests": "1",
"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/68.0.3440.106 Safari/537.36"),
"Accept": ("text/html,application/xhtml+xml,"
"application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"),
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8"
}
import urllib
url = "https://www.amazon.com/" req = HTTPRequest(url=url, method="GET", headers=myheaders, follow_redirects=True, request_timeout=20, connect_timeout=10,proxy_host="127.0.0.1",
proxy_port=8888,ca_certs="FiddlerRoot.pem") # 绑定证书
response = yield c.fetch(req) # 发起请求
print response.code
print response.body
IOLoop.current().stop() # 停止ioloop线程
except:
print traceback.format_exc()
Fiddler抓到的报文(说明可以正常访问)
四、总结
抓取量少的时候,建议使用requests,简单易用。
并发量大的时候,建议使用tornado,单线程高并发,高效易编程。
以上给出了requests和Fiddler中常用的接口和参数说明,能解决爬虫面对的大部分问题,包括并发抓取、日常的反爬应对,https网站的抓取。
附上一段我自己的常用抓取代码逻辑:
import randomfrom tornado.ioloop import IOLoopfrom tornado import genfrom tornado.queues import Queue import random
from tornado.ioloop import IOLoop
from tornado import gen
from tornado.queues import Queue TASK_QUE = Queue(maxsize=1000) def response_handler(res):
""" 处理应答,一般会把解析的新的url添加到任务队列中,并且解析出目标数据 """
pass @gen.coroutine
def url_fetcher_without_param():
pass @gen.coroutine
def url_fetcher(*args,**kwargs):
global TASK_QUE
c = CurlAsyncHTTPClient() while 1:
#console_show_log("Let's spider")
try:
param = TASK_QUE.get(time.time() + 300) # 5 分钟超时
except tornado.util.TimeoutError::
yield gen.sleep(random.randint(10,100))
continue try:
req = HTTPRequest(url,method=,headers=,....) # 按需配置参数
response = yield c.fetch(req)
if response.coe==200:
response_handler(response.body)
except Exception:
yield gen.sleep(10)
continue
finally:
print "I am a slow spider"
yield gen.sleep(random.randint(10,100)) @gen.coroutine
def period_callback():
pass def main():
io_loop = IOLoop.current()
# 添加并发逻辑1
io_loop.spawn_callback(url_fetcher, 1)
io_loop.spawn_callback(url_fetcher, 2)
io_loop.spawn_callback(url_fetcher_without_param) # 参数是可选的 # 如果需要周期调用,调用PeriodicCallback:
PERIOD_CALLBACK_MILSEC = 10 # 10, 单位ms
io_loop.PeriodicCallback(period_callback,).start()
io_loop.start() if __name__ == "__main__":
main()
以上,欢迎讨论交流
五、参考:
requests快速入门:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
requests高级应用:http://docs.python-requests.org/en/master/user/advanced/
什么是CA_BUNDLE:https://www.namecheap.com/support/knowledgebase/article.aspx/986/69/what-is-ca-bundle
如何用requests下载图片:https://stackoverflow.com/questions/13137817/how-to-download-image-using-requests
tornado AsyncHttpClient: https://www.tornadoweb.org/en/stable/httpclient.html
100 Continue状态码:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status/100
HTTP认证: https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication
证书转换: https://www.alibabacloud.com/help/zh/faq-detail/40526.htm
网易云免费体验馆,0成本体验20+款云产品!
更多网易研发、产品、运营经验分享请访问网易云社区。
相关文章:
【推荐】 分布式存储系统可靠性系列二:系统估算示例
【推荐】 网易云数据库架构设计实践
爬虫开发python工具包介绍 (4)的更多相关文章
- 爬虫开发python工具包介绍 (1)
本文来自网易云社区 作者:王涛 本文大纲: 简易介绍今天要讲解的两个爬虫开发的python库 详细介绍 requests库及函数中的各个参数 详细介绍 tornado 中的httpcilent的应用 ...
- 爬虫开发python工具包介绍 (2)
本文来自网易云社区 作者:王涛 可选参数我们一一介绍一下: 参数 释义 示例 params 生成url中?号后面的查询Key=value 示例1: >>>payload = {'ke ...
- 爬虫开发python工具包介绍 (3)
本文来自网易云社区 作者:王涛 :arg str url: URL to fetch :arg str method: HTTP method, e.g. " ...
- Python爬虫开发与项目实战
Python爬虫开发与项目实战(高清版)PDF 百度网盘 链接:https://pan.baidu.com/s/1MFexF6S4No_FtC5U2GCKqQ 提取码:gtz1 复制这段内容后打开百度 ...
- Python 3网络爬虫开发实战》中文PDF+源代码+书籍软件包
Python 3网络爬虫开发实战>中文PDF+源代码+书籍软件包 下载:正在上传请稍后... 本书书籍软件包为本人原创,在这个时间就是金钱的时代,有些软件下起来是很麻烦的,真的可以为你们节省很多 ...
- Python 3网络爬虫开发实战中文 书籍软件包(原创)
Python 3网络爬虫开发实战中文 书籍软件包(原创) 本书书籍软件包为本人原创,想学爬虫的朋友你们的福利来了.软件包包含了该书籍所需的所有软件. 因为软件导致这个文件比较大,所以百度网盘没有加速的 ...
- Python 3网络爬虫开发实战中文PDF+源代码+书籍软件包(免费赠送)+崔庆才
Python 3网络爬虫开发实战中文PDF+源代码+书籍软件包+崔庆才 下载: 链接:https://pan.baidu.com/s/1H-VrvrT7wE9-CW2Dy2p0qA 提取码:35go ...
- 《Python 3网络爬虫开发实战中文》超清PDF+源代码+书籍软件包
<Python 3网络爬虫开发实战中文>PDF+源代码+书籍软件包 下载: 链接:https://pan.baidu.com/s/18yqCr7i9x_vTazuMPzL23Q 提取码:i ...
- Python 3网络爬虫开发实战书籍
Python 3网络爬虫开发实战书籍,教你学会如何用Python 3开发爬虫 本书介绍了如何利用Python 3开发网络爬虫,书中首先介绍了环境配置和基础知识,然后讨论了urllib.reques ...
随机推荐
- 142. O(1)时间检测2的幂次
用 O(1) 时间检测整数 n 是否是 2 的幂次. 您在真实的面试中是否遇到过这个题? Yes 样例 n=4,返回 true; n=5,返回 false. class Solution { publ ...
- js将数字转换为带有单位的中文表示
好不容易找到了, 实测可行, 记录一下. 到时候调用方法 addChineseUnit , 其他两个方法在addChineseUnit中有调用 /** * 为数字加上单位:万或亿 * * 例如 ...
- Spring框架学习——AOP的开发
一.AOP开发中的相关术语. ——JoinPoint(连接点):指那些可以被拦截到的点.比如增删改查方法都可以增强,这些方法就可以被称为是连接点. ——PointCut:切入点,真正被拦截的点,指对哪 ...
- uvm_verision——告诉我你几岁了?
uvm_version 定义了UVM相关的版本信息,而具体的uvm_revision则是通过在src/macros/uvm_version_defines.svh实现的. uvm_revision_s ...
- 非常实用的Linux 系统监控工具
随着互联网行业的不断发展,各种监控工具多得不可胜数.这里列出网上最全的监控工具.让你可以拥有超过80种方式来管理你的机器.在本文中,我们主要包括以下方面: 命令行工具 网络相关内容 系统相关的监控工具 ...
- 微软爆料新型系统,Windows7,Windows10强势来袭
本系统是10月5日最新完整版本的Windows10 安装版镜像,win10正式版,更新了重要补丁,提升应用加载速度,微软和百度今天宣布达成合作,百度成为win10 Edge浏览器中国默认主页和搜索引擎 ...
- 交互干货必收 | App界面交互设计规范
原文地址:http://www.woshipm.com/ucd/193776.html
- 用cssText批量修改样式
一般情况下我们用js设置元素对象的样式会使用这样的形式: var element= document.getElementById(“id”);element.style.width=”20px”;e ...
- WPF使用附加属性绑定,解决data grid列绑定不上的问题
背景 需要对datagrid的列header添加自定义属性,然后绑定,并根据不同的列header绑定不同的值,传统的加扩展类太麻烦,而附加属性的特点更适用于这种场景. 1.xaml 代码 <Da ...
- Android之通过adb shell 模拟器 error: more than one device and emulator 改ip dns
error: more than one device and emulator 如果出现上面那种情况 请关闭 ide 输入下面的 再次重新启动 模拟器 如果实际上只有一个设备或模拟器,并且查到有 ...