1.配置环境
安装python,urllib,BeautifulSoup4.
pip是python的安装程序。
验证安装是否成功:
- urllib
- from urllib.request import urlopen
- BeautifulSoup4
- from bs4 import BeautifulSoup
安装BeautifulSoup4
linux:
sudo apt-get install python-bs4
Mac:
sudo easy_install pip
pip install beautfulsoup4
windows
pip install beautfiulsoup4
pip3 install beautifulsoup4
1.urllib用法
轻松模拟浏览器
导入urllib库的request模块
from urllib import request请求URL
resp = request.urlopen(‘http://www.baidu.com‘)使用响应对象输出数据
print(resp.read().decode(“utf-8”))
from urllib import request
resp=request.urlopen("www.baidu.com")
print(resp.read().decode("utf-8")) #尝试一下print(resp),print(resp.read()),还有print(resp.read().decode('utf-8'))分别都是什么样子的。
- 模拟真实的浏览器
1, 携带User-Agent头
req=request.Request(url)
req.add_header(key,value)
resp=request.urlopen(req)
print(resp.read().decode(“utf-8”))
2,使用POST
- 导入urllib库下面的parse
from urllib import parse - 使用urlencode生成post数据
postData=parse.urlencode([
(key1,val1),
(key2,val2),
(keyn,valn)
]) - 使用postData发送post请求
request.urlopen(req,data=postData,encode(“utf-8”))