py3 BeautifulSoup 利器 html 解析器使用

BeautitulSoup Html 解析器

import requests

from bs4 import BeautifulSoup

url = "http://www.baidu.com"
contents = requests.get(url).content
soup = BeautifulSoup(contents, 'lxml')
contents = soup.prettify()

>>> soup.link
<link href="http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css"/>
>>> soup.title
<title>\u767e\u5ea6\u4e00\u4e0b\uff0c\u4f60\u5c31\u77e5\u9053</title>
>>> soup.link.name
'link'
>>> soup.link.attrs
{'href': 'http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css', 'type': 'text/css', 'rel': ['stylesheet']}
>>> soup.link.attrs.get('type')
'text/css'
>>> soup.link.attrs['href']
'http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css'


>>> for node in soup.head.contents:
...     print(node)
...     
... 
<meta content="text/html;charset=utf-8" http-equiv="content-type"/>
<meta content="IE=Edge" http-equiv="X-UA-Compatible"/>
<meta content="always" name="referrer"/>
<link href="http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type=""/>
<title>百度一下,你就知道</title>


>>> for node in soup.head.contents:
...     if node.name == "meta":
...         print(node)
...     if node.name == "title":
...         print node.string
...         
...     
... 
<meta content="text/html;charset=utf-8" http-equiv="content-type"/>
<meta content="IE=Edge" http-equiv="X-UA-Compatible"/>
<meta content="always" name="referrer"/>
百度一下,你就知道
>>> tags = soup.find_all(name='meta')
>>> tags
[<meta content="text/html;charset=unicode-escape" http-equiv="content-type"/>, <meta content="IE=Edge" http-equiv="X-UA-Compatibl
e"/>, <meta content="always" name="referrer"/>]


>>> import re
>>> tags = soup.find_all(re.compile('^me.*'))
>>> tags
[<meta content="text/html;charset=unicode-escape" http-equiv="content-type"/>, <meta content="IE=Edge" http-equiv="X-UA-Compatibl
e"/>, <meta content="always" name="referrer"/>]
>>> for tag in tags:
...     print(tag)
...     
... 
<meta content="text/html;charset=utf-8" http-equiv="content-type"/>
<meta content="IE=Edge" http-equiv="X-UA-Compatible"/>
<meta content="always" name="referrer"/>
>>> tags = soup.find_all(re.compile('^me.*'), content="always")
>>> for tag in tags:
...     print(tag)
...     
... 
<meta content="always" name="referrer"/>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值