首页 > 解决方案 > WebScraping - 从 td 类中提取值

问题描述

我正在尝试编写一个简单的 Py 网络抓取文件来从网页上的表格中提取特定值,但结果并没有以当前的形式出现。我想我在使用 soup.find 命令时做错了什么。

URL = 'https://www.health.nsw.gov.au/news/Pages/20200329_01.aspx'
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')

results = soup.find('td', class_='moh-rteTableFooterOddCol-6')
print(results)

我期待 93,099 的值,但打印提供了结果

<td class="moh-rteTableFooterOddCol-6">93,099</td>

我也无法将结果格式转换为字符串。

截图以防万一 截图以防万一

标签: pythonweb-scrapingbeautifulsoup

解决方案


您可以使用contents属性访问它。

import requests
from bs4 import BeautifulSoup

URL = 'https://www.health.nsw.gov.au/news/Pages/20200329_01.aspx'
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')

results = soup.find('td', class_='moh-rteTableFooterOddCol-6')
if results and results.contents :
   print(int(results.contents[0].replace(',','')))

将来,每当您不知道返回的对象的属性时,都可以使用该对象__dict__进行解码。

举个例子,

>> results.__dict__
{'attrs': {'class': ['moh-rteTableFooterOddCol-6']},
 'can_be_empty_element': False,
 'cdata_list_attributes': {'*': ['class', 'accesskey', 'dropzone'],
  'a': ['rel', 'rev'],
  'area': ['rel'],
  'form': ['accept-charset'],
  'icon': ['sizes'],
  'iframe': ['sandbox'],
  'link': ['rel', 'rev'],
  'object': ['archive'],
  'output': ['for'],
  'td': ['headers'],
  'th': ['headers']},
 'contents': ['93,099'],
 'hidden': False,
 'known_xml': False,
 'name': 'td',
 'namespace': None,
 'next_element': '93,099',
 'next_sibling': None,
 'parent': <tr class="moh-rteTableFooterRow-6"><td class="moh-rteTableFooterEvenCol-6">Total</td>
 <td class="moh-rteTableFooterOddCol-6">93,099</td></tr>,
 'parser_class': bs4.BeautifulSoup,
 'prefix': None,
 'preserve_whitespace_tags': {'pre', 'textarea'},
 'previous_element': '\n',
 'previous_sibling': '\n',
 'sourceline': 1075,
 'sourcepos': 0}

推荐阅读