python(23)-爬虫-BeautifulSoup

     从网页上获取数据是种常用的技能。从网页上得到的其实就是一个长长的html或者是lxml格式的字符串。对这个字符串的解析就可以用BeautifulSoup。

1.下载安装
2.语法
3.使用示例


1.下载安装 :
         pip install BeautifulSoup 即可。
         如果你安装了anaconda3.7版本,可以不用装了。
2.语法

1.创建对象
   bs=BeautifulSoup{
        url,
        html_parser,   指定解析器
        encoding      //指定编码格式
    }
2.找到节点find
<a href='a.html' class='a_link'> next_page</a>
bs.find_all('a')
bs.find_all('a',href='a.html')
bs.find_all('a',href='a.html',string="next page")
bs.find_all('a',class_='a_link')
bs.find_all('a',{'class':'a_link'})


3.使用示例
 

import requests
import bs4

def getSoup():
    r = requests.get(url, timeout=30)
    soup=BeautifulSoup(r.text,'lxml')
    div_list=soup.find_all('div',{'class':'span1'})
    city_api=[]
    for i in range(8):
        div_conent = div_list[i]
        caption = div_conent.find('div',{'class':'caption'}).text.strip()
        value= div_conent.find('div',{'class':'caption'}).text.strip()
        city_api.append((caption,value))

if __name__=="__main__":
   getSoup()

就是这么简单。

posted @ 2019-12-29 09:20  jasmineTang  阅读(61)  评论(0)    收藏  举报