python爬虫学习7
目录
import urllib.request
url = 'https://www.baidu.com'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 SLBrowser/7.0.0.12151 SLBChan/11'}
# 构建请求对象
req = urllib.request.Request(url,headers=headers)
# 获取opener对象
opener = urllib.request.build_opener()
resp = opener.open(req)
print(resp.read().decode('utf-8'))
运行结果:
-
使用Cookie
# 使用Cookie需要用到相关的 Handler。 import http.cookiejar,urllib.request url = 'https://www.baidu.com' headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 SLBrowser/7.0.0.12151 SLBChan/11'} req = urllib.request.Request(url,headers=headers) # 声明CookieJar对象 cookie = http.cookiejar.CookieJar() # 利用 HTTPCookieProcessor 构件一个 Handler handler = urllib.request.HTTPCookieProcessor(cookie) # 构件 opener opener = urllib.request.build_opener(handler) resp = opener.open(req) for i in cookie: print(i.name+'='+i.value)
运行结果:
import http.cookiejar,urllib.request filename = 'cookie.txt' url = 'https://www.baidu.com' # 获取 cookie def get_cookie(): # 实例化一个 MozillaCookieJar cookie = http.cookiejar.MozillaCookieJar(filename) # 创建 Handler handler = urllib.request.HTTPCookieProcessor(cookie) # 构件 opener opener = urllib.request.build_opener(handler) # 发送请求 resp = opener.open(url) # 存储 cookie.save() if __name__ == '__main__': get_cookie()
运行后可以看到当前目录下出现了一个名为cookie.txt的文件,打开后内容如下:
未完,明日继续,,,