04. urllib库的高级用法
1. 伪装自己
有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作
1.1 设置请求头
其中User-Agent
代表用的哪个请求的浏览器
代码如下:
1 | from urllib.request import urlopen |
对付防盗链,服务器会识别headers中的referer是不是它自己,如果不是,有的服务器不会响应,所以我们还可以在headers中加入referer
代码如下:
1 | headers = { |
import urllib.request
import random
ua_list = [
“Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)”,
“Mozilla/5.0 (Windows; U; Windows NT 5.2) Gecko/2008070208 Firefox/3.0.1”,
“Mozilla/5.0 (Windows; U; Windows NT 5.2) AppleWebKit/525.13 (KHTML, like Gecko) Version/3.1”,
“Mozilla/5.0 (Windows; U; Windows NT 5.2) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27”,
“Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; QIHU 360EE)”
]
user_agent = random.choice(ua_list)
request = urllib.request.Request(“http://www.baidu.com")
request.add_header(“User-Agent”,user_agent)
#区分大小写
print(request.get_header(“User-agent”))
1 | --- |
from urllib.request import ProxyHandler
from urllib.request import build_opener
proxy = ProxyHandler({“http”: “119.109.197.195:80”})
opener = build_opener(proxy)
url = “http://www.baidu.com"
response = opener.open(url)
print(response.read().decode(“utf-8”))
1 |
|
from urllib.request import HTTPHandler
from urllib.request import build_opener
from urllib.request import Request
handler = HTTPHandler(debuglevel=1)
opener = build_opener(handler)
url = “http://www.sohu.com"
request = Request(url)
response = opener.open(request)
```