写一个Python的bs4模块的demo
以下是一个简单的Python bs4模块的演示,它将从HTML文件中提取所有链接:
from bs4 import BeautifulSoup
import requests
url = 'http://example.com'
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
links = []
for link in soup.find_all('a'):
href = link.get('href')
if href is not None:
links.append(href)
print(links)
解释:
- 引入了bs4模块和requests模块,前者用于解析HTML文档,后者用于获取HTML文档;
- 定义了要提取链接的网站URL;
- 使用requests模块获取HTML文档,并将其存储为字符串;
- 使用BeautifulSoup模块将HTML文档解析为BeautifulSoup对象,以便于后续的操作;
- 使用find_all()方法查找HTML文档中所有的链接,并将其存储在一个列表中;
- 打印所有链接。
原文地址: https://www.cveoy.top/t/topic/bqia 著作权归作者所有。请勿转载和采集!