python - 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>
我也无法将结果格式转换为字符串。
解决方案
您可以使用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}
推荐阅读
- json - 为什么我的 facebook 应用程序无法接收网页 webhook?
- xml - 使用 XSLT 和 XSLT 1.0 (MSXML 6) 从 XML 输出文本
- pandas - 在 df2 中从 df1 中找到一个值并替换匹配行的其他值
- javascript - 查找所有带有转义公式的单元格 '=
- plot - 在 gnuplot 中的标签上添加彩色线?
- android - onPrepareOptionMenu menu?.findItem 返回 null android
- c# - 如何在 Xamarin Forms android 应用程序中显示本地化异常消息
- android - Android获取相机视图周围的死区大小
- c# - 将 DelegatingHandler 与 HttpClient 上的自定义数据一起使用
- sapui5 - 过滤由多个实体集组成的 SmartTable