BeautifulSoup 库最常用的对象恰好就是 BeautifulSoup 对象。
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page1.html")
bsObj = BeautifulSoup(html.read())
print(bsObj.h1
输出结果:
<h1>An Interesting Title</h1>
我们导入 urlopen
,然后调用 html.read()
获取网页的 HTML 内容。这样就可以把 HTML 内容传到 BeautifulSoup 对象,转换成下面的结构:
• html → <html><head>...</head><body>...</body></html>
— head → <head><title>A Useful Page<title></head>
— title → <title>A Useful Page</title>
— body → <body><h1>An Int...</h1><div>Lorem ip...</div></body>
— h1 → <h1>An Interesting Title</h1>
— div → <div>Lorem Ipsum dolor...</div>
可以看出,我们从网页中提取的 <h1>
标签被嵌在 BeautifulSoup 对象 bsObj
结构的第二层(html → body → h1)。但是,当我们从对象里提取 h1 标签的时候,可以直接调用它:
bsObj.h1
其实,下面的所有函数调用都可以产生同样的结果:
bsObj.html.body.h1
bsObj.body.h1
bsObj.html.h1
其实,任何 HTML(或 XML)文件的任意节点信息都可以被提取出来,只要目标信息的旁边或附近有标记就行。