python beautifulsoup get html tag content



如何获取带有 beautifulsoup 的 html 标签的内容? 例如<title>标签的内容?

我试过了:

from bs4 import BeautifulSoup
url ='http://www.websiteaddress.com'
soup = BeautifulSoup(url)
result = soup.findAll('title')
for each in result:
    print(each.get_text())

但什么也没发生。我正在使用python3。

您需要先获取网站数据。您可以使用urllib.request模块执行此操作。请注意,HTML 文档只有一个标题,因此无需使用find_all()和循环。

from urllib.request import urlopen
from bs4 import BeautifulSoup
url ='http://www.websiteaddress.com'
data = urlopen(url)
soup = BeautifulSoup(data, 'html.parser')
result = soup.find('title')
print(result.get_text())

最新更新