【问题标题】:Need help extracting 4 numbers from HTML pull in python需要帮助从 python 中提取 4 个数字
【发布时间】:2021-11-20 00:38:52
【问题描述】:

我现在编写了打开 URL 并将 HTML 数据提取到 htmlA 的代码

htmlA内我试图提取4条信息

  1. 约会
  2. 价格 1
  3. 价格2
  4. 百分比

嵌入这4条信息的htmlA部分如下所示:

<!-- TAB CONTENT -->\r\n\t\t\t<div class="fund-content tab-content span12">\r\n\r\n\t\t\t\t<!-- OVERVIEW -->\r\n\t\t\t\t<div class="tab-pane active" id="overview">\r\n\t\t\t\t\t<h3 class="subhead tab-header">Overview</h3>\r\n\t\t\t\t\t<div class="row-fluid">\r\n\t\t\t\t\t\t<div class="span6">\r\n\t\t\t\t\t\t\t<p class="as-of-date">\r\n\t\t\t\t\t\t\t\t<span id="ContentPlaceHolder1_cph_main_cph_main_AsOfLabel">As of 9/24/2021</span>\r\n\t\t\t\t\t\t\t</p>\r\n\r\n\t\t\t\t\t\t\t<div class="table-wrapper">\r\n\t\t\t\t\t\t\t\t<div>\r\n\t<table class="cefconnect-table-1 table table-striped" cellspacing="0" cellpadding="5" Border="0" id="ContentPlaceHolder1_cph_main_cph_main_SummaryGrid">\r\n\t\t<tr class="tr-header">\r\n\t\t\t<th scope="col">&nbsp;</th><th class="right-align" scope="col">Share<br>Price</th><th class="right-align" scope="col">NAV</th><th class="right-align" scope="col">Premium/<br>Discount</th>\r\n\t\t</tr><tr>\r\n\t\t\t<td>Current</td><td class="right-align">$19.14</td><td class="right-align">$21.82</td><td class="right-align">-12.28%</

在这个例子中我要提取:

  1. 2021 年 9 月 24 日
  2. 19.14 美元
  3. 21.82 美元
  4. -12.28%

我正在尝试使用 BeautifulSoup 搜索和提取 htmlA,但在挑选出我需要的特定信息位(第 4 位)时遇到了麻烦。有人可以帮我编写执行此操作的代码吗?非常感谢!

【问题讨论】:

  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: python html web-scraping data-extraction information-extraction


【解决方案1】:

我不能给你一个完整的答案,但我可以为你指明正确的方向。

您需要将 html 内容解析为 BeautifulSoup 对象才能以 Python 方式处理网页内容。像这样,

from bs4 import BeautifulSoup
import requests


url = 'https://en.wikipedia.org/wiki/Elon_Musk'

html = requests.get(url)

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

一旦你有了 var soup,你就可以调用各种方法,比如,

print(soup.div) 

这会给你一个 div 元素,等等。

更多示例:

soup.title
# <title>The Dormouse's story</title>

soup.title.name
# u'title'

soup.title.string
# u'The Dormouse's story'

soup.title.parent.name
# u'head'

soup.p
# <p class="title"><b>The Dormouse's story</b></p>

soup.p['class']
# u'title'

soup.a
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

soup.find_all('a')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

soup.find(id="link3")
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>

来自https://www.crummy.com/software/BeautifulSoup/bs4/doc/

【讨论】:

  • 我尝试使用您描述的方法,但 URL 阻止/拒绝它。我想我需要一种方法来使用上面帖子中的原始方式进行提取,还有其他想法吗?感谢您的帮助!
  • 您可以发布您已有的代码吗?另外,您收到的完整错误消息是什么?最后,您尝试从哪个 URL 抓取数据?
猜你喜欢
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多