作业1.2-爬取商品信息

网站

作业1.2-爬取商品信息_第1张图片
Paste_Image.png

代码

from bs4 import BeautifulSoup
info = []
with open('D:/Plan-for-combating-master/week1/1_2/1_2answer_of_homework/index.html','r') as wb_data:
    soup = BeautifulSoup(wb_data, 'lxml')
    images = soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > img')
    titles = soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.caption > h4:nth-of-type(2) > a')
    prices = soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.caption > h4.pull-right')
    stars = soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.ratings > p:nth-of-type(2)')
    reviews = soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.ratings > p.pull-right')

for title,image,price,star,review in zip(titles,images,prices,stars,reviews):
    data = { 
       'title':title.get_text(), 
       'image':image.get('src'),
       'price':price.get_text().replace('$',''),
       'star':len(star.find_all('span', class_='glyphicon glyphicon-star')),
       'review':review.get_text().split()[0]
    }
    info.append(data)

print(info)

问题

  • 从网页上直接copy selector时,有个div标签序号是错的。应该是1,copy下来的结果是2。最开始没有意识到,出来的结果一直有错...后来一步步检查才发现,不知道为何网页自动copy的也会出这种错呢?
  • 想到一个问题:如果一个标签A下,有B/C/D三个并列的标签,但我只想爬取B/D两个标签下的内容。如何在select的时候选中这特定的两个标签呢?因为要么就限制selector末端为A,但这样就把三个都抓进去了。不知道一个标签下存在三个并列的不同标签,是否是一个合理的html格式。

总结

  • 限制标签顺序的时候可以用A.class_name,也可以用A.nth-of-type(n)。直接从网页上copy的selector是nth-child(n),可能会报错,需要注意。
  • find_all方法查找特定标签里的内容时,可以根据class名称查找,此时class要加一个下划线class_
  • 总结起来就是,先用beautifulsoap将网页的内容读入,再根据select的参数将想要的标签内容提取出来成为一个list,最后在这些list里再使用各种方法获取标签里面的内容就可以了。有的是直接get_text获取标签内的文本信息,图片一般是get('src)等等。当然,根据你拿到的信息,可以再做一些别的字符串处理,最终呈现想要的结果输出就可以了。

沈 阅
20160826

你可能感兴趣的:(作业1.2-爬取商品信息)