Python实战(三)——Python解析器 BeautifulSoup使用

    xiaoxiao2021-03-25  174

    一、安装

    1、进入python安装目录,如果scripts文件中有pip.exe则直接cmd 执行 pip install beautifulsoup4,开始安装

    2、验证安装是否成功

     

    #coding :utf-8 import bs4 print bs4 #返回bs4信息,,<module 'bs4' from 'C:\Python27\lib\site-packages\bs4\__init__.pyc'>

    返回bs4模块信息,beautifulsoup安装成功。

     

    二、网页解析

     

    from bs4 import BeautifulSoup import re html_doc=""" """ #创建bs对象 soup=BeautifulSoup(html_doc,'html_parser',from_encoding='uft-8') #html内容,解析器,编码 #获取所有url links=soup.find_all('a') for link in links: print link.name,link['href'],link.get_text() #获取指定url link=soup.find('a',href='http://baidu.com') print link.name,link['href'],link.get_text() #根据正则表达式筛选 link=soup.find('p',href=re.compile(r"titl")) print link.name,link['href'],link.get_text() #获取p段落文字 p_node=soup.find('p',class_='title') # a标签里的class名="title" print p_node.name,p_node.get_text()

     

     

     

     

     

     

     

     

    转载请注明原文地址: https://ju.6miu.com/read-1242.html

    最新回复(0)