Beautiful Soup 4(BS4)是一个Python库,用于从HTML和XML文件中提取数据。它创建了一个解析树,从中可以轻松地提取和操作数据。以下是如何使用BS4和Python抓取网页上的表格数据(例如livetable)的基本步骤:
html.parser
,还有lxml
和html5lib
。html.parser
(Python内置),lxml
(速度快,支持XPath),html5lib
(容错性好,生成HTML5格式的文档)。以下是一个简单的示例,展示如何使用BS4抓取网页上的表格数据:
import requests
from bs4 import BeautifulSoup
# 目标网页URL
url = 'http://example.com/livetable'
# 发送HTTP请求
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 使用BeautifulSoup解析HTML内容
soup = BeautifulSoup(response.text, 'html.parser')
# 假设表格的id是'live-table'
table = soup.find('table', {'id': 'live-table'})
# 获取所有的行
rows = table.find_all('tr')
# 遍历行并提取数据
for row in rows:
cols = row.find_all(['td', 'th'])
cols = [ele.text.strip() for ele in cols]
print(cols)
else:
print(f'Failed to retrieve the webpage. Status code: {response.status_code}')
response.encoding = 'gbk'
。请注意,抓取网站数据时应遵守网站的使用条款,并尊重版权和隐私政策。不要抓取受版权保护的内容或个人数据。
领取专属 10元无门槛券
手把手带您无忧上云