码迷,mamicode.com
首页 > 编程语言 > 详细

用python的BeautifulSoup分析京东html

时间:2015-03-18 06:22:14      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:

之前用python爬取网页的时候,一直用的是regex或者自带的库sgmllib里的SGMLParser。但是遇到复杂一点的情况时,SGMLParser往往就不那么给力了!(哈,难道说我 too native了?毕竟beautifulSoup是继承sgmlparser的么~)所以,我寻寻觅觅寻寻觅觅,发现了BeautifulSoup这么个玩意。BeautifulSoup提供了很人性化的parser tree,有了它,我们可以简单的抽取出tagname, attrs, text等等等等...

  install什么的,看这里 -> http://www.crummy.com/software/BeautifulSoup/,这里我使用的是pip安装,直接执行如下命令即可:

# sudo pip install beautifulsoup

采集代码如下:

# -*- coding:utf-8 -*-

from bs4 import BeautifulSoup
import urllib2,sys

reload(sys)
sys.setdefaultencoding("utf-8")
#伪造的header
headers = {User-Agent:Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36}
#抓取地址 读入页面源文件
fromurl=http://item.jd.com/1479933933.html
r = urllib2.Request(url=fromurl, headers=headers)
response = urllib2.urlopen(r)
page=response.read()
#实例化BS对象
soup= BeautifulSoup(page)
#定位到微博信息主节点 页面中每一条微博是它的子节点
name_tags = soup.find_all(name=div, attrs={id:name})
for name in name_tags:
    product_name = name.find(name=h1).get_text()
    print 产品名称:  + product_name

price_tags = soup.find_all(name=div, attrs={id:summary-price})
for price in price_tags:
    product_price = price.find(name=strong, attrs={id:jd-price}).get_text()
    print 产品价格:  + product_price #此处有问题,因为这个是ajax处理的,所以还需要进一步处理

 

在程序调试过程中,出现错误提示:ImportError: No module named bs4,后来发现是版本不对,卸载掉就版本,安装新版本即可

# sudo pip uninstall beautifulsoup
# sudo pip install beautifulsoup4

另外在调试过程中,也出现了编码问题,错误提示:UnicodeEncodeError: ‘ascii‘ codec can‘t encode characters in position 0-3: ordinal not in range(128),解决的方法是在文本的前两行加入:

import sys

reload(sys)
sys.setdefaultencoding("utf-8")

即可。

用python的BeautifulSoup分析京东html

标签:

原文地址:http://www.cnblogs.com/zl0372/p/BeautifulSoup.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!