用Python学爬虫,第一周第二课练习题:难点在于统计星星的个数

2016-10-11  本文已影响0人  张强1007

进入麻瓜编程用python学爬虫第一周第二课的练习题了,自己鼓捣了半天,无解,最后可耻的看了答案:恍然大悟后发现自己没有真正领会标签后面的描述的真正意思。

爬取本地网页信息

我的代码:

from bs4 import BeautifulSoup

with open('/home/steven/Downloads/Plan-for-combating-master/week1/1_2/1_2answer_of_homework/1_2_homework_required/index.html','r') as wb_data:

    Soup = BeautifulSoup(wb_data,'lxml')

images = Soup.select('body > div > div > div.col-md-9 > div > div > div > img')
prices = Soup.select('body > div > div > div.col-md-9 > div > div > div > div.caption > h4.pull-right')
titles = Soup.select('body > div > div > div.col-md-9 > div > div > div > div.caption > h4 > a')
reviews = Soup.select('body > div > div > div.col-md-9 > div > div > div > div.ratings > p.pull-right')
stars = Soup.select('div.col-sm-4 > div > div > p:nth-of-type(2)')

for image,price,title,review,star in zip(images,prices,titles,reviews,stars):
    data= {
        'image': image.get('src'),
        'price': price.get_text(),
        'title': title.get_text(),
        'review': review.get_text(),
        'star': len(star.find_all('span',class_='glyphicon glyphicon-star'))

    }

    print(data)

这行代码stars = Soup.select('div.col-sm-4 > div > div > p:nth-of-type(2)') 是这道题的关键点之一。

接着来到第二个关键点:如何使用过滤过的信息,统计星星的个数。

看一下程序运行结果:

/usr/bin/python3.5 "/home/steven/Downloads/Plan-for-combating-master/week1/1_2/1_2answer_of_homework/1.2 new.py"
{'title': 'EarPod', 'price': '$24.99', 'review': '65 reviews', 'image': 'img/pic_0000_073a9256d9624c92a05dc680fc28865f.jpg', 'star': 5}
{'title': 'New Pocket', 'price': '$64.99', 'review': '12 reviews', 'image': 'img/pic_0005_828148335519990171_c234285520ff.jpg', 'star': 4}
{'title': 'New sunglasses', 'price': '$74.99', 'review': '31 reviews', 'image': 'img/pic_0006_949802399717918904_339a16e02268.jpg', 'star': 4}
{'title': 'Art Cup', 'price': '$84.99', 'review': '6 reviews', 'image': 'img/pic_0008_975641865984412951_ade7a767cfc8.jpg', 'star': 3}
{'title': 'iphone gamepad', 'price': '$94.99', 'review': '18 reviews', 'image': 'img/pic_0001_160243060888837960_1c3bcd26f5fe.jpg', 'star': 4}
{'title': 'Best Bed', 'price': '$214.5', 'review': '18 reviews', 'image': 'img/pic_0002_556261037783915561_bf22b24b9e4e.jpg', 'star': 4}
{'title': 'iWatch', 'price': '$500', 'review': '35 reviews', 'image': 'img/pic_0011_1032030741401174813_4e43d182fce7.jpg', 'star': 4}
{'title': 'Park tickets', 'price': '$15.5', 'review': '8 reviews', 'image': 'img/pic_0010_1027323963916688311_09cc2d7648d9.jpg', 'star': 4}

Process finished with exit code 0

总结:

上一篇 下一篇

猜你喜欢

热点阅读