The website is API(1)
Requests 自动爬取HTML页面 自动网路请求提交
robots 网络爬虫排除标准
Beautiful Soup 解析HTML页面
实战
Re 正则表达式详解提取页面关键信息
Scrapy*框架
第一周:规则
第一单元:Requests库入门
1.安装
以管理员身份运行命令提示符
输入 pip install request
验证:
>>> import requests
>>> r = requests.get("http://www.baidu.com")
>>> r.status_code
200
requests.request():构造一个请求,支撑以各个方法的基础方法
requests.get():获取HTML网页的主要方法,对应于HTTP的GET
requests.get(url,params=None,**kwargs)
url:拟获取页面的url链接
params:url中的额外参数,字典或字节流格式,可选
**kwargs:12个控制访问的参数
Response对象的属性
r.status_code:HTTP请求的返回状态,200表示连接成功,404表示失败
r.text:HTTP响应内容的字符串形式,即,url对应的页面内容
r.encoding:从HTTP header中猜测的响应内容编码方式
r.apparent_encoding:从内容中分析出响应内容编码方式
r.content:HTTP响应内容的二进制形式
通用代码框架:
>>> import requests
>>> def getHTMLText(url):
try:
r = requests.get(url,timeout=30)
r.raise_for_status()#如果状态不是200,引发HTTPEorror异常
r.encoding = r.apparent_encoding
return r.text
except:
return "产生异常"
>>> if __name__ == "__main__":
url="www.baidu.com"
print(getHTMLText(url))
产生异常
requests.head():网页头,HEAD
requests.post():向HTML网页提交POST请求的方法,POST
requests.put():PUT
requests.patch():局部修改请求,PATCH
requests.delete():删除请求,DELETE
requests.request(method,url,**kwargs)
method:请求方式,对应get/put/post等七种
r = requests.request('GET',url,**kwargs)
r = requests.request('HEAD',url,**kwargs)
r = requests.request('POST',url,**kwargs)
r = requests.request('PUT',url,**kwargs)
r = requests.request('PATCH',url,**kwargs)
r = requests.request('delete',url,**kwargs)
r = requests.request('OPTIONS',url,**kwargs)
**kwargs:控制访问的参数,可选
params:字典或字节序列,作为参数增加到url中
data:字典、字节序列或文件对象,作为Request的内容
json:JSON格式的数据
headers:
https://www.baidu.com/robots.txt
Requests库爬取实例
>>> import requests
>>> url = "https://item.jd.com/2967929.html"
>>> try:
r = requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
print(r.text[:1000])
except:
print("爬取失败") <!DOCTYPE HTML>
<html lang="zh-CN">
<head>
<!-- shouji -->
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>【华为荣耀8】荣耀8 4GB+64GB 全网通4G手机 魅海蓝【行情 报价 价格 评测】-京东</title>
<meta name="keywords" content="HUAWEI荣耀8,华为荣耀8,华为荣耀8报价,HUAWEI荣耀8报价"/>
<meta name="description" content="【华为荣耀8】京东JD.COM提供华为荣耀8正品行货,并包括HUAWEI荣耀8网购指南,以及华为荣耀8图片、荣耀8参数、荣耀8评论、荣耀8心得、荣耀8技巧等信息,网购华为荣耀8上京东,放心又轻松" />
<meta name="format-detection" content="telephone=no">
<meta http-equiv="mobile-agent" content="format=xhtml; url=//item.m.jd.com/product/2967929.html">
<meta http-equiv="mobile-agent" content="format=html5; url=//item.m.jd.com/product/2967929.html">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<link rel="canonical" href="//item.jd.com/2967929.html"/>
<link rel="dns-prefetch" href="//misc.360buyimg.com"/>
<link rel="dns-prefetch" href="//static.360buyimg.com"/>
<link rel="dns-prefetch" href="//img10.360buyimg.com"/>
<link rel="dns
>>> import requests
>>> url = "https://www.amazon.cn/gp/product/B01MBL5Z3Y"
>>> try:
kv = {'user-agent':'Mozilla/5.0'}
r = requests.get(url,headers = kv)
r.raise_for_status()
r.encoding = r.apparent_encoding
print(r.text[1000:2000])
except:
print("Fail") ue_sid = (document.cookie.match(/session-id=([0-9-]+)/) || [])[1],
ue_sn = "opfcaptcha.amazon.cn",
ue_id = 'HB12BAYVB85FMA4VRS38';
}
</script>
</head>
<body> <!--
To discuss automated access to Amazon data please contact api-services-support@amazon.com.
For information about migrating to our APIs refer to our Marketplace APIs at https://developer.amazonservices.com.cn/index.html/ref=rm_c_sv, or our Product Advertising API at https://associates.amazon.cn/gp/advertising/api/detail/main.html/ref=rm_c_ac for advertising use cases.
--> <!--
Correios.DoNotSend
--> <div class="a-container a-padding-double-large" style="min-width:350px;padding:44px 0 !important"> <div class="a-row a-spacing-double-large" style="width: 350px; margin: 0 auto"> <div class="a-row a-spacing-medium a-text-center"><i class="a-icon a-logo"></i></div> <div class="a-box a-alert a-alert-info a-spacing-base">
<div class="a-box-inner">
百度360搜索关键词提交
import requests
keyword = 'Python'
try:
kv = {'q':keyword}
r = requests.get("http://www.so.com/s",params = kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except:
print("爬取失败")
图片下载
import requests
import os
url = "http://wx1.sinaimg.cn/mw600/0076BSS5ly1g6hmmj82tpj30u018wdos.jpg"
root = "E://pics//"
path = root + url.split('/')[-1]
try:
if not os.path.exists(root):
os.mkdir(root)
if not os.path.exists(path):
r = requests.get(url)
with open(path,'wb') as f:
f.write(r.content)
f.close()
print("文件保存成功")
else:
print("文件已存在")
except:
print("爬取失败")
IP地址查询
import requests
url = "http://m.ip138.com/ip.asp?ip="
try:
r = requests.get(url+'202.204.80.112')
r.raise_for_status()
r.encoding = r.apparent_encoding
print(r.text[-300:])
except:
print("爬取失败")
The website is API(1)的更多相关文章
- The website is API(2)
一.Beautifu Soup库 from bs4 import BeautifulSoup soup = BeautifulSoup(demo,"html.parser") Ta ...
- The website is API(3)
网络爬虫实战知识准备: Requests库.robots(网络爬虫排除标准).BeautifulSoup库 一.Re正则表达式 1. 简洁地表达一组字符串 通用的字符串表达框架 字符串匹配 编译: 2 ...
- The website is API(4)
1.淘宝商品信息定向爬虫 目标:获取淘宝搜索页面信息,提取其中的商品名称和价格 理解:淘宝的搜索接口 翻页的处理 技术路线:requests+re https://s.taobao.com/searc ...
- 我这么玩Web Api(二):数据验证,全局数据验证与单元测试
目录 一.模型状态 - ModelState 二.数据注解 - Data Annotations 三.自定义数据注解 四.全局数据验证 五.单元测试 一.模型状态 - ModelState 我理解 ...
- [Android]使用Dagger 2依赖注入 - API(翻译)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5092525.html 使用Dagger 2依赖注入 - API ...
- [转]ASP.NET Web API(三):安全验证之使用摘要认证(digest authentication)
本文转自:http://www.cnblogs.com/parry/p/ASPNET_MVC_Web_API_digest_authentication.html 在前一篇文章中,主要讨论了使用HTT ...
- ASP.NET Web API(三):安全验证之使用摘要认证(digest authentication)
在前一篇文章中,主要讨论了使用HTTP基本认证的方法,因为HTTP基本认证的方式决定了它在安全性方面存在很大的问题,所以接下来看看另一种验证的方式:digest authentication,即摘要认 ...
- ASP.NET Web API(二):安全验证之使用HTTP基本认证
在前一篇文章ASP.NET Web API(一):使用初探,GET和POST数据中,我们初步接触了微软的REST API: Web API. 我们在接触了Web API的后就立马发现了有安全验证的需求 ...
- 微信公众平台Js API(WeixinApi)
微信公众平台Js API(WeixinApi): https://github.com/zxlie/WeixinApi#user-content-3%E9%9A%90%E8%97%8F%E5%BA%9 ...
随机推荐
- request和response的setCharacterEncoding()方法
1.pageEncoding=”UTF-8”的作用是设置JSP编译成Servlet时使用的编码.2.contentType=”text/html;charset=UTF-8”的作用是指定服务器响应给浏 ...
- Android自定义View——简单实现边缘凹凸电子票效果
View继承LinearLayout,在View的上下边缘画出白色的圆形即可,这里只要计算出圆的个数和圆的循环规律即可,下面请看分析 我们取卡片的前2个凹凸来看,将其分为四部分,并且两部分为循 ...
- POJ 1547:Clay Bully
Clay Bully Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 8349 Accepted: 4711 Descri ...
- 合并排序_python
#!/usr/bin/python # --coding:utf-8 -- def sort_merge(left,right): i,j=0,0 result=[] while i<len(l ...
- 19 01 13 JQery 加载 选择器 样式操作
在Javascript 中应该用下方法经行编辑 <script type="text/javascript" src="js/jquery-1.12.4.min ...
- 使用super调用被子类覆盖的父类方法
1.没有super方法 /* * 子类方法覆盖父类方法,用super方法可以调用父类被覆盖的方法 */ class fruit{ public fruit() { System.out.println ...
- ES6 之 Integer数据类型
1.简介(仅仅是提案) js所有数字都保存成64为浮点数,这就决定了整数的精确程度只能到53个二进制位. 大于这个范围的整数,js是无法精确表示的,这使得js不合适进行科学和金融方面的精确计算. 故引 ...
- delphi try except与try finally语句用法以及区别
一.异常的来源 在Delphi的应用程序中,下列的情况都比较有可能产生异常. (1)文件处理 (2)内存分配 (3)Windows资源 (4)运行时创建对象和窗体 (5)硬件和操作系统冲突 二.异常的 ...
- 用Axure画原型图有感
感觉前端做UE非常有优势啊- 但是在制作的时候,似乎陷入了误区: (1)只求原型图的漂亮,色彩丰富,忽略了其本质作用,是用来整理逻辑,画出逻辑流程的. (2)一开始就追求交互,高保真的原型,忽视了细节 ...
- main函数的参数(int argc,char *argv[])
一般的main函数都是不带参数的,因此main 后的括号都是空括号.实际上,main函数可以带参数,这个参数可以认为是 main函数的形式参数.C语言规定main函数的参数只能有两个, 习惯上这两个参 ...