【跟我学Python】第三章.使用Python解析网页

                           

                                   【跟我学Python】第三章.场景三-- 使用Python解析抓取网页

 

使用Python访问网页主要有三种方式: urllib, urllib2, httplib

urllib比较简单,功能相对也比较弱,httplib简单强大,但好像不支持session


1. 最简单的页面访问
res=urllib2.urlopen(url)
print res.read()


2. 加上要get或post的数据
data={"name":"hank", "passwd":"hjz"}
urllib2.urlopen(url, urllib.urlencode(data))


3. 加上http头
header={"User-Agent": "Mozilla-Firefox5.0"}
urllib2.urlopen(url, urllib.urlencode(data), header)

 

更为复杂的操作:使用opener和handler协助操作其它web资源
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)


4. 加上session
cj = cookielib.CookieJar()
cjhandler=urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cjhandler)
urllib2.install_opener(opener)


5. 加上Basic认证
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://www.163.com/"
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)


6. 使用代理
proxy_support = urllib2.ProxyHandler({"http":"http://1.2.3.4:3128/"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)


7. 设置超时
socket.setdefaulttimeout(5)

 

 

场景三:用Python写一个秒杀脚本,能够对淘宝特定页面进行解析

 

proxy_support = urllib2.ProxyHandler({"http":"http://proxy.****.com/"})
opener = urllib2.build_opener(proxy_support)
 urllib2.install_opener(opener)
 res = urllib2.urlopen('http://www.taobao.com/')
 print res.read() #将读取得到整个html页面

#接下来使用beautifulsoup扩展库对html中特定的div进行解析
from bs4 import *
soup = BeautifulSoup(res.read( ))
print(soup.find(id="div1")) #得到id=div1的div

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值