美文网首页
Python实战:爬取商品信息

Python实战:爬取商品信息

作者: Privilege | 来源:发表于2016-09-25 13:09 被阅读0次
    思路:
    • 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字典打印是无序的,如果想要一个特定的顺序,那么应该在使用前自己对它们排序。
    

    相关文章

      网友评论

          本文标题:Python实战:爬取商品信息

          本文链接:https://www.haomeiwen.com/subject/ogrfyttx.html