URL
- URL的一般格式为(带方括号[]的为可选项):
protocol://hostname[:port]/path/[;parameters][?query]#fragment
- URL 由三部分组成:
- 第一部分是协议:http,https,ftp,file,ed2k…
- 第二部分是存放资源的服务器的域名系统或IP地址(有时候要包含端口号,各种传输协议都有默认的端口,如http的默认端口是80)
- 第三部分是资源的具体地址,如目录或者文件名等
urllib
里面有四大模块:
- urllib.request for opening and reading URLs
- urllib.error containing the exceptions raised by urllib.request
- urllib.parse for parsing URLs # 解析URL
- urllib.robotparser for parsing robots.txt files
实例一:
import urllib.request
response = urllib.request.urlopen("http://www.fishc.com")
html = response.read()
print(html) # 二进制数据
html = html.decode("utf-8") # 解码操作
print(html)
实例二:
在placekitten网站下载一只猫的图片
#爬虫下载猫
import urllib.request
response = urllib.request.urlopen('http://placekitten.com/g/500/600')
cat_img = response.read()
with open ('cat_500_600.jpg','wb') as f:
f.write(cat_img)
实例三:
利用有道词典翻译文本
import urllib.request
import urllib.parse
import json
content = input("请输入需要翻译的内容:")
url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
data={}
data['type']= 'AUTO'
data['i'] = content
data['doctype']= 'json'
data['xmlVersion'] = 1.8
data['keyfrom'] ='fanyi.web'
data['ue'] = 'UTF-8'
data['typoResult']='true'
data = urllib.parse.urlencode(data).encode('utf-8')
response = urllib.request.urlopen(url,data)
html = response.read().decode('utf-8')
target = json.loads(html)
print("翻译结果为:%s"%(target['translateResult'][0][0]['tgt']))
隐藏
修改headers:
1.通过 request 的 headers 参数修改
2.通过 request.add_header()方法修改
防止被发现办法:
1.延时爬取(time.sleep()模块)
2.使用代理
步骤:
1.参数是一个字典{ ‘类型’ : ‘代理ip:端口号’ }
proxy_support = urllib.request.ProxyHandler({})
2.定制、使用一个 opener
opener = urllib.request.build_opener(proxy_support)
3a.安装 opener
urllib.request.install_opener(opener)
3b.调用 opener
opener.open(url)