Python中HTML与XML处理全解析
1. 使用BeautifulSoup解析HTML
BeautifulSoup是Python中一个强大的HTML解析库,下面是一个使用它的典型示例,用于从网页抓取内容、解析并输出其中的HTTP超链接。
1.1 Python 2代码示例
import urllib, urlparse, bs4
f = urllib.urlopen('http://www.python.org')
b = bs4.BeautifulSoup(f)
seen = set()
for anchor in b('a'):
url = anchor.get('href')
if url is None or url in seen: continue
seen.add(url)
pieces = urlparse.urlparse(url)
if pieces[0]=='http':
print(urlparse.urlunparse(pieces))
1.2 Python 3代码示例
在Python 3中, urlopen 函数位于 urllib.request 模块, urlparse 和 urlunparse 函数位于 urllib.parse 模块。
Python HTML与XML处理详解
超级会员免费看
订阅专栏 解锁全文
2631

被折叠的 条评论
为什么被折叠?



