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 ...
随机推荐
- spring boot2 运行环境
1.springboot个版本系统需求 spring boot maven jdk 内置tomcat 内置jetty servlet 2.0.x 3.2+ 8或9 8.5(3.1) 9.4(3.1) ...
- [GXYCTF2019]Ping Ping Ping
0x00 知识点 命令执行变量拼接 /?ip=127.0.0.1;a=g;cat$IFS$1fla$a.php 过滤bash用sh执行 echo$IFS$1Y2F0IGZsYWcucGhw|base6 ...
- UVA - 10934 Dropping water balloons(装满水的气球)(dp)
题意:有k个气球,n层楼,求出至少需要多少次实验能确定气球的硬度.气球不会被实验所“磨损”. 分析: 1.dp[i][j]表示第i个气球,测试j次所能确定的最高楼层. 2.假设第i-1个气球测试j-1 ...
- Java算法练习——寻找两个有序数组的中位数
题目链接 题目描述 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2. 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 $O(log(m + n))$. 你可以假设 nu ...
- 连接mysql的各种方式
mysql连接操作是客户端进程与mysql数据库实例进程进行通信.从程序设计角度来说,属于进程通信,常用进程通信包括: 管道.Tcp/Ip 套接字.UNIX域套接字. 1.TCP/IP (1)使用最多 ...
- LCA--P3379 【模板】最近公共祖先(LCA)
题目描述 如题,给定一棵有根多叉树,请求出指定两个点直接最近的公共祖先. 输入格式 第一行包含三个正整数 N,M,S,分别表示树的结点个数.询问的个数和树根结点的序号. 接下来 N−1 行每行包含两个 ...
- PAT Advanced 1094 The Largest Generation (25) [BFS,DFS,树的遍历]
题目 A family hierarchy is usually presented by a pedigree tree where all the nodes on the same level ...
- HDU-2087 C - 剪花布条(KMP基本)
http://acm.hdu.edu.cn/showproblem.php?pid=2087 一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案.对于给定的花布条和小饰条,计算一下能 ...
- Linux 基本操作学习
Linux 学习 虚拟机 (Virtual Machine) 指通过软件模拟的具有完整硬件系统功能的,运行再一个完全隔离环境中的完整计算机系统 常用 Linux 命令 命令 对应英文 作用 ls li ...
- LeetCode——230. 二叉搜索树中第K小的元素
给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素. 说明: 你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数. 示例 1: 输入: root = ...