python爬虫
1.ProxyHandler处理器(代理):
1. 代理的原理:在请求目的网站之前,先请求代理服务器,然后让代理服务器去请求目的网站,代理
服务器拿到目的网站的数据后,再转发给我们的代码。
2. http://httpbin.org:这个网站可以方便的查看http请求的一些参数。
3. 在代码中使用代理:
使用 urllib.request.ProxyHandler ,传入一个代理,这个代理是一个字典,字典的key依
赖于代理服务器能够接收的类型,一般是 http 或者 https ,值是 ip:port 。
使用上一步创建的 handler ,以及 request.build_opener 创建一个 opener 对象。
使用上一步创建的 opener ,调用 open 函数,发起请求。
示例代码如下:
2. requests请求
发送get请求:
发送get请求,直接调用 requests.get 就可以了。想要发送什么类型的请求,就调用什么方法。
response的一些属性:
from urllib import request
url = 'http://httpbin.org/ip'
# 1. 使用ProxyHandler,传入代理构建一个handler
handler = request.ProxyHandler({"http":"223.241.78.43:8010"})
# 2. 使用上面创建的handler构建一个opener
opener = request.build_opener(handler)
# 3. 使用opener去发送一个请求
resp = opener.open(url)
print(resp.read())
response = requests.get("https://www.baidu.com/")
import requests
kw = {'wd':'中国'}
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
# params 接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode()
response = requests.get("http://www.baidu.com/s", params = kw, headers =
headers)
# 查看响应内容,response.text 返回的是Unicode格式的数据
print(response.text)