一. 预备知识
1. 初识 http
- 协议名: http
- 主机名:blog.aaa.com
- 端口:80
- 路径: /aa-alan
网页另存为, 就属于爬虫。 如果很多个网页,每次都另存为,则显得很麻烦。
# python3的urllib2与urllib合并
import urllib.request as spider
# urlopen()函数用于实现对目标url的访问
headers = {'User-Agent':'Mozilla/5.0 3578.98 Safari/537.36'}
url = "//www.greatytc.com/p/ec0f0b87b34f"
url = spider.Request(url, headers=headers)
res = spider.urlopen(url)
ret = res.read().decode('utf-8')
print(ret)
response = urllib.request.urlopen("http://www.fishc.com",)
html = response.read()
#print(html) # bytes
# decode utf-8
html = html.decode("utf-8")
print(html)
# 参考文档
#1 - https://blog.csdn.net/The_Time_Runner/article/details/86522700?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
#2 - https://blog.csdn.net/NeverLate_gogogo/article/details/88417936
2. python 如何访问互联网?
- urllib : url + lib
- url 的一般格式为(带[]的为可选项):
protcocol://hostname[:port] / path / [;parameters][?query]#fragment - url 由3部分组成:
- 第一部分是协议: http / https / ftp / file /ed2k ...
- 第二部分为存放资源的服务器的域名系统或IP地址。
#1. 抓取一张图片
import urllib.request
response = urllib.request.urlopen("http://placekitten.com/500/760")
cat_img = response.read()
with open('cat_500600.jpg', 'wb') as f:
f.write(cat_img)
#2. 利用有道词典翻译
```python
import urllib.request
import urllib.parse
import json
content = input("请输入需要翻译的内容:")
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
data = {}
data["i"] = content #"我爱中国"
data["from"] = "AUTO"
data["to"] = "AUTO"
data["smartresult"] = "dict"
data["client"] = "fanyideskweb"
data["salt"] = "15834926807363"
data["sign"] = "937448b30a8475cbf70d5239627352d3"
data["ts"] = "1583492680736"
data["bv"] = "bc250de095a39eeec212da07435b6924"
data["doctype"] = "json"
data["version"] = "2.1"
data["keyfrom"] = "fanyi.web"
data["action"] = "FY_BY_CLICKBUTTION"
data["action"] = "FY_BY_CLICKBUTTION"
data = urllib.parse.urlencode(data).encode("utf-8")
response = urllib.request.urlopen(url, data)
html = response.read().decode("utf-8")
# print(html)
target = json.loads(html)
# print(type(target))
# print(target['translateResult'])
# print(type(target['translateResult']))
# print(target['translateResult'][0][0]['tgt'])
print("翻译结果:%s" % (target['translateResult'][0][0]['tgt']))
二. 隐藏
防止server 认为“用户”,非人操作(短期内频繁访问server),拒绝服务。 针对这种情况,通常有两种方法。
- 延迟发送;
- 使用代理