首页 > 解决方案 > 在 Python 中使用某些文本抓取 HTML 表格

问题描述

我正在尝试使用 python 抓取 HTML 表格。HTML 页面中有很多表格,但我只想抓取某个表格。我正在用漂亮的汤来做这个网页抓取。

我的代码如下所示:

page = get("http://uobgoldprice.com/history/2018/September/10/")
html = BeautifulSoup(page.content, 'html.parser')

for p in html.select('tr'):
    if p.text == "ARGOR CAST BAR":
        print (p.text)

我只想要显示“截至 2018 年 9 月 10 日星期一的费率”的表格。

我该怎么做呢?

标签: pythonhtmlweb-scrapinghtml-table

解决方案


您需要找到包含文本的元素以及作为表格的父元素:

import re
import requests
from bs4 import BeautifulSoup

page = requests.get("http://uobgoldprice.com/history/2018/September/10/")
html = BeautifulSoup(page.content, 'html.parser')

element = html.find(text=re.compile('Rate as at Monday, 10 September 2018'))
print(element.findParent('table'))

推荐阅读