Scrapying
URL的一般格式为(带方括号[]的为可选项):
protocol :// hostname[:port] / path / \[;parameters][?query]#fragment
URL由三部分组成:
–第一部分是协议:http,https,ftp,file,ed2k…
–第二部分是存放资源的服务器的域名系统或IP地址(有时候要包含端口号,各种传输协议都有默认的端口号,如http的默认端口为80)。
–第三部分是资源的具体地址,如目录或文件名等。
下载猫的图片
import urllib.request
response = urllib.request.urlopen("http://placekitten.com/g/200/300")
# 相当于下面两句
# req = urllib.request.Request("http://placekitten.com/g/200/300")
# response = urllib.request.urlopen(req)
cat_img = response.read()
# 其它函数:response.geturl(), response.info(), response.getcode()
with open('cat_200_300.jpg', 'wb') as f:
f.write(cat_img)隐藏
通过Request的headers参数修改
通过Request.add_header()方法修改
有道翻译
代理 步骤:
参数是一个字典 {‘类型’:‘代理ip:端口号’}
proxy_support = urllib.request.ProxyHandler({})
定制、创建一个 opener
opener = urllib.request.build_opener(proxy_support)
3a. 安装 opener,永久性
urllib.request.install_opener(opener)
3b. 调用 opener,每次调用
opener.open(url)
图片下载实例
异常处理
处理异常的第一种写法
处理异常的第二种写法
##Scrapy
使用Scrapy抓取一个网站一共需要四个步骤:
– 创建一个Scrapy项目;
– 定义Item容器;
– 编写爬虫;
– 存储内容。
Last updated
Was this helpful?