Python实战:爬取商品信息

思路:
  • step 1:打开网页
  • step 2:用BeautifulSoup的select()方法得到所需要的元素(爬取信息)
  • step 3:用for xxx in zip(xxx)打包不同元素(整理信息)
难点:
  • 统计★的个数
结果展示:
总结:
  1. 对于本地html文件,用open()打开,不用requests.get()打开
  2. 我发现对于一个元素的位置,不必将整条路径给出,只需将能确定元素位置的路径给出即可。同时,对于复制元素selector的路径,出现的div:nth-child(2),应改为div:nth-of-type(2)。还有,如果需要一对多,改为div即可
  3. find_all()方法,详见http://www.cnblogs.com/yupeng/p/3362031.html
  4. 得到了一个tag,要得到它里面的属性,比如说"class"属性,就可以有三种方法。
    1.用tag["class"]得到
    2.用tag.get('class')得到
    3.用tag.attrs(['class'])得到
  5. 打印python字典,内容将是无序的,如果想要一个特定的顺序,那么应该在使用前自己对它们排序。
  6. get_text()函数必须是soup类型才可以用,其余的不行,用之前需要先看下是不是soup类型,不然会报错
  7. if 语句判断字符串相等:
    == 用来判断两个对象的值是否相等
    is 相等代表两个对象的 id 相同(从底层来看的话,可以看作引用同一块内存区域)
我的代码:
from bs4 import BeautifulSoup
import requests
url = 'C:\\Users\\58472\\Desktop\\Python爬虫\\Plan-for-combating-master\\week1\\1_2\\1_2answer_of_homework\\index.html'
#wb_data = requests.get(url)
#print(wb_data)
#对于本地文件,用open()打开,不用requests.get()打开
with open(url,'r') as wb_data:
    soup = BeautifulSoup(wb_data,'lxml')
    images = soup.select('div.col-md-9 > div:nth-of-type(2) > div > div > img')
    prices = soup.select('div.col-md-9 > div:nth-of-type(2) > div > div > div.caption > h4.pull-right')
    titles = soup.select('div.col-md-9 > div:nth-of-type(2) > div > div > div.caption > h4:nth-of-type(2) > a')
    rates = soup.select('div.col-md-9 > div:nth-of-type(2) > div > div > div.ratings > p.pull-right')
    stars_tags = soup.find_all("span",{"class":{"glyphicon glyphicon-star","glyphicon glyphicon-star-empty"}})
    stars = []
    for star in stars_tags:
        stars.append(star['class'][1]) #这种方法能够获得tag的'class'中的值!!!
    num_stars = []
    for index in range(0,int(len(stars)/5)):
        alist = stars[index*5:index*5+5]
        num_stars.append('★'*alist.count('glyphicon-star')+'☆'*alist.count('glyphicon-star-empty')) #数组的count方法
    for image, price, title, rate, num_star in zip(images,prices,titles,rates,num_stars):
        data = {
            'image': image.get('src'),
            'price': price.get_text(),
            'title': title.get_text(),
            'rate':rate.get_text(),
            'stars':num_star
        }
        print(data) #发现每次运行的结果,顺序都不同,觉得很奇怪!!!  python字典打印是无序的,如果想要一个特定的顺序,那么应该在使用前自己对它们排序。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 关于bs4,官方文档的介绍已经非常详细了,传送:Beautifulsoup 4官方文档,这里我把它组织成自己已经消...
    徐薇薇阅读 10,845评论 0 1
  • Date:2016-9-21update:2016-9-30By:Black Crow 前言: 终于进入到网络页面...
    black_crow阅读 4,507评论 0 2
  • 出现的问题: 当爬取交易地点,使用代码 时,爬取的结果是 ['交易地点:'],而不是我想要的‘地点-地点’形式 ...
    鸣人吃土豆阅读 5,104评论 1 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,461评论 19 139
  • 鸳鸯是贾府的家生女儿,她的父亲金彩是贾府的仆人,她生而为贾府的仆人。 因言语爽利、行事妥当,鸳鸯被...
    琳琅书影阅读 3,294评论 0 0