Python爬虫学习之路——python IED工具介绍(一)
爬虫定义
@百度百科:网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。另外一些不常使用的名字还有蚂蚁、自动索引、模拟程序或者蠕虫。
@菜鸟联盟:一段自动抓取互联网信息的程序,从互联网上抓取对于我们有价值的信息
@JiChao_Song:在遵守robots协议的前提下,从特定URL中,获取特定的信息并保存的过程
robots协议定义
定义:全称是网络爬虫排除标准”(Robots Exclusion Protocol),网站通过Robots协议告诉搜索引擎哪些页面可以抓取,哪些页面不能抓取。(robots.txt)
User-agent: Baiduspider
Allow: /article
Allow: /oshtml
Allow: /ershou
Allow: /$
Disallow: /product/
Disallow: /
User-Agent: Googlebot
Allow: /article
Allow: /oshtml
Allow: /product
Allow: /spu
Allow: /dianpu
Allow: /oversea
Allow: /list
Allow: /ershou
Allow: /$
Disallow: /
User-agent: Bingbot
Allow: /article
Allow: /oshtml
Allow: /product
Allow: /spu
Allow: /dianpu
Allow: /oversea
Allow: /list
Allow: /ershou
Allow: /$
Disallow: /
User-Agent: 360Spider
Allow: /article
Allow: /oshtml
Allow: /ershou
Disallow: /
User-Agent: Yisouspider
Allow: /article
Allow: /oshtml
Allow: /ershou
Disallow: /
User-Agent: Sogouspider
Allow: /article
Allow: /oshtml
Allow: /product
Allow: /ershou
Disallow: /
User-Agent: Yahoo! Slurp
Allow: /product
Allow: /spu
Allow: /dianpu
Allow: /oversea
Allow: /list
Allow: /ershou
Allow: /$
Disallow: /
User-Agent: *
Disallow: /
爬虫的基本流程
1.发起HTTP请求
引入库来发送HTTP请求
Resquests库 | urllib.requset库 |
---|---|
import requests | import urllib.request |
requests.get(“http://www.baidu.com/”) | urllib.requset.urlopen(“http://www.baidu.com/”) |
2.获取响应内容
Resquests库 | urllib.requset库 |
---|---|
import requests | import urllib.request |
r = requests.get(“http://www.baidu.com/”) | r = urllib.requset.urlopen(“http://www.baidu.com/”) |
print(r.text) | print(r.read()) |
3.分析和提取响应内容
常见的三种页面解析和提取方法
re | lxml | BeautifulSoup |
---|
4.存储内容
实例:爬取中关村桌面壁纸并保存到本地
import requests
import re
from PIL import Image
from io import BytesIO
#发送HTTP请求
url = 'http://desk.zol.com.cn/'
print(url)
r = requests.get(url)
# 正则表达提取
pat = r'src="(.*?).jpg"'
# 正则匹配
result = re.compile(pat).findall(r.text)
# print(result)
# 输出提取结果数
x = 0
for i in result:
# print(i)
a = i + ".jpg"
print(a)
response = requests.get(a)
image = Image.open(BytesIO(response.content))
image.save('D:\python入门\博客\壁纸\%s.jpg' % x)
x = x + 1