从零开始学Python-3(Request 入门的小案例)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了从零开始学Python-3(Request 入门的小案例),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2270字,纯文字阅读大概需要4分钟。
内容图文
![从零开始学Python-3(Request 入门的小案例)](/upload/InfoBanner/zyjiaocheng/635/ae3860eee18c435ab829da093f05730a.jpg)
本文是在Mooc上学习Python的笔记,原题如下
http://www.icourse163.org/course/BIT-1001870001
Robots协议
作用:
网站告知网络爬虫哪些页面可以抓取,哪些不行
形式:
在网站根目录下的robots.txt文件
例如
结果如下
User-agent: *
Disallow: /?*
Disallow: /pop/*.html
Disallow: /pinpai/*.html?*
User-agent: EtaoSpider
Disallow: /
User-agent: HuihuiSpider
Disallow: /
User-agent: GwdangSpider
Disallow: /
User-agent: WochachaSpider
Disallow: /
注释,*代表所有,/代表根目录
User‐agent: *
Disallow: /
五个Requests库网络爬取的小例子
例子一 京东商品爬取
import requests
url = 'http://www.icourse163.org/course/BIT-1001870001'
try:
r = requests.get(url)
r.raise_for_status() #Raises stored HTTPError, if one occurred.
#如果发生了HTTP错误,就把这个错误存储起来
r.encoding = r.apparent_encoding
print(r.text[:1000])
except:
print('爬取失败')
例子二 爬取不允许爬虫访问的亚马逊
import requests
url = 'https://www.amazon.cn/dp/B01MSKJZ5J/ref=lp_1753445071_1_1?s=shoes&ie=UTF8&qid=1587470105&sr=1-1'
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('爬取失败')
例子三 百度搜索全代码
import requests
keyword = 'Python'
try:
kv = {'wd':keyword} #字典或字节序列,作为参数增加到url中
r = requests.get('http://www.baidu.com/s',params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except:
print('爬取失败')
例子四 网络图片的爬取和存储
import requests
import os
url = 'http://img0.dili360.com/pic/2020/04/21/5e9ea4243bfc74p24083429.jpg@!rw9'
root = 'F://pics//'
path = root + url.split('/')[-1]
try:
if not os.path.exists(root): #如果不存在这个路径的话
os.mkdir(root) #创建这个路径
print('存在这个路径')
if not os.path.exists(path): #如果这个文件不存在
r = requests.get(url)
with open(path,'wb') as f:
f.write(r.content) #把content写入content里面
f.close()
print('文件保存成功')
else:
print('文件已存在')
except:
print('爬取失败')
例子五 IP地址归属地的自动查询
import requests
url = 'http://m.ip138.com/ip.asp?ip=' #获取ip的url
try:
r = requests.get(url+'202.204.80.112')
r.raise_for_status()
r.encoding = r.apparent_encoding
print(r.text[-500:])
except:
print('爬取失败')
内容总结
以上是互联网集市为您收集整理的从零开始学Python-3(Request 入门的小案例)全部内容,希望文章能够帮你解决从零开始学Python-3(Request 入门的小案例)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。