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"/>