BeautifulSoup模块的使用

"DOM"

# -*- encoding:utf-8 -*-

#BeautifulSoup操作DOM
#导入urllib2,BeautifulSoup,re模块
from bs4 import BeautifulSoup
import urllib2,re


#BeautifulSoup官方文档
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""


#获取baidu页面DOM操作对象
Response=urllib2.Request("http://www.badiu.com")
url=urllib2.urlopen(Response)
badiu_html=url.read()
#print(badiu_html)
#获取baidu页面的全部a节点的name,href,text

soup=BeautifulSoup(html_doc,'html.parser',from_encoding='utf-8')
#异常处理获取不到的节点
try:
nodeall=soup.find_all('a')
for link in nodeall:
print(link.name,link['href'],link.get_text())
except:
print('key wrong')
#正则获取单个p节点
p_node=soup.find('p',class_=re.compile('to'))
print(p_node.name,p_node.get_text())

扫描二维码关注公众号,回复: 2180842 查看本文章

猜你喜欢

转载自www.cnblogs.com/activecode/p/9317533.html