python 数据采集入门

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”))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值