Python网络爬虫信息提取mooc代码实例

这篇文章主要介绍了python网络爬虫与信息提取mooc,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考

实例一–爬取页面

import requests
url="https//itemjd.com/2646846.html"
try:
 r=requests.get(url)
 r.raise_for_status()
 r.encoding=r.apparent_encoding
 print(r.text[:1000])
except:
 print("爬取失败")

正常页面爬取

实例二–爬取页面

import requests
url="https://www.amazon.cn/gp/product/B01M8L5Z3Y"
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("爬取失败")

对访问用户名有限制,模拟浏览器对网站请求

实例三–爬取搜索引擎

#百度的关键词接口:http://www.baidu.com/s?wd=keyword
#360的关键词接口:http://www.so.com/s?q=keyword
import requests
keyword="python"
try:
 kv={'wd':keyword}
 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
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://image.nationalgeographic.com.cn/2017/0211/20170211061910157.jpg"
root="F://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地址归属地查询:

http://m.ip138.com/ip.asp?ip=ipaddress

url="http://www.ip138.com/iplookup.asp?ip="
try:
 r=requests.get(url+'202.204.80.112'+'&action=2')
 r.raise_for_status()
 r.encoding=r.apparent_encoding
 print(r.text[-500:])
except:
 print("爬取失败")

内容就以上怎么多,最后给大家推荐一个口碑不错的公众号【程序员学府】,这里有很多的老前辈学习技巧,学习心得,面试技巧,职场经历等分享,更为大家精心准备了零基础入门资料,实战项目资料,每天都有程序员定时讲解Python技术,分享一些学习的方法和需要留意的小细节

在这里插入图片描述

发布了20 篇原创文章 · 获赞 0 · 访问量 3620

猜你喜欢

转载自blog.csdn.net/chengxun02/article/details/104998851