【Beautiful Soup 初探】

前沿

网络爬虫分为API接口爬取和web爬取,一般的流程是先将需要的字段读取出来,形成一个目标json文件,最后通过scrapy设置Item,pipline,将资源文件保存下来。

1.beautiful soup是什么?

beautiful soup是一个可以从HTML或XML中提取标签数据的Python库。在网页爬取的时候,第一种方式,将html或xml转为json操作,第二种方式,直接去读取标签内容,这个时候就需要beautiful soup。

2.如何使用

2.1 引入库

from bs4 import BeautifulSoup

2.2 使用xpath获取到目标的html标签(这是一个大列表)

 def parse(self, response):
        sel = Selector(response)
        goodItems = sel.xpath('//*[@id="collection"]/div[5]/div/div').extract()
 pass

2.3 使用beautiful soup解析获取每个Item

  for item in goodItems:
            soup = BeautifulSoup(item, 'html.parser')
            #获取商品图片的URL
            goodImgUrlNode = soup.find(class_='product_img_url not-rotation img-responsive front')
            goodImgUrl = goodImgUrlNode.get('src')
            print('goodImgUrl===='+goodImgUrl)
          #获取商品标题
          ...
          #获取商品价格
          ...

2.4 开始爬取,下载图片

 yield ImgsItem(image_name=self.goodTitle,image_urls=['https:'+goodImgUrl])

3.beautiful soup 基础

3.1 对象的种类
Tag , NavigableString , BeautifulSoup , Comment

3.2 遍历文档树
子节点/父节点/兄弟节点/回退和前进

3.3 搜索文档树
过滤器/find_all()/find()/find_parents()/find_parent()...

3.4 输出
格式化输出 prettify() ,每个标签占一行
压缩输出 unicode() 或 str()
得到tag中包含的文本内容,可以用get_text(),可以使用分割线soup.get_text("|")

3.5 编码
任何HTML或XML文档都有自己的编码方式,比如ASCII 或 UTF-8,但是使用Beautiful Soup解析后,文档都被转换成了Unicode:

-- end --

个人作品1:(匿名聊天)
http://im.meetyy.cn/

个人作品2:(单身交友)


【Beautiful Soup 初探】_第1张图片
公众号Meetyy

你可能感兴趣的:(【Beautiful Soup 初探】)