【问题标题】:Trying to pull data from a poorly formatted HTML website试图从格式不佳的 HTML 网站中提取数据
【发布时间】:2016-07-03 14:54:09
【问题描述】:

我最近一直在尝试从一个网站上提取信息,虽然我取得了很大的成功,但还是有点困难。

我目前一直在使用 Regex 来查找一些信息(这里是我想查看的名称)

webAddress = 'http://meridian.puzzlepirates.com/yoweb/crew/info.wm?crewid=' + str(crewid)
htmlFile = urllib.urlopen(webAddress)
htmlText = htmlFile.read()

regex = 'classic&target=(.+?)">'
pattern = re.compile(regex)
checkMatch = re.findall(pattern,htmlText)

像这样。当该特定行上有一致的指标时,这很好用。但是我现在有一个问题,我的指标不在那条线上。

 <td width="28" height="28"><a href="/ratings/top_5_0.html"><img 
  src="/yoweb/images/stat-5.png" width="28" height="28" border="0"
  alt="Gunning"></a></td>
<td align="left">
  <font size="-1">
      <i><b>Exalted</b></i>/<b>Master</b>
  </font>

特别想拉倒倒数第二行,但倒数第二行可能不是粗体或斜体/没有相同的单词,所以我的指标必须是“Gunning”,因为是我关心的特定领域。不幸的是,它甚至不总是在每个不同页面的同一行,所以我不能只看一个特定的行来尝试找到它。任何建议都会很棒!

编辑

我已经开始尝试学习/使用 Beautiful Soup(感谢您为我指明方向。

我一开始并没有想的那么清楚,所以让我试着澄清一下。

特别想从this之类的页面中提取排名

 <td width="28" height="28"><a href="/ratings/top_5_0.html"><img 
  src="/yoweb/images/stat-5.png" width="28" height="28" border="0"
  alt="Gunning"></a></td>
<td align="left">
  <font size="-1">
      <i><b>Exalted</b></i>/<b>Master</b>
  </font>

上面是我特别查找的部分的 HTML,并且格式并不总是相同(例如,它可能是非粗体、粗体或粗体和斜体。所以我不太确定我使用哪种方法可以用来可靠地从该信息中提取特定的统计信息。

我也尝试通过字体大小进行隔离,但结果数量不一致,因此我无法隔离我想要的特定统计信息。

【问题讨论】:

标签: python html regex html-parsing pull


【解决方案1】:

标记肯定不好处理,但你肯定should not be approaching it with regular expressions。 不要仅仅因为你熟悉或擅长使用某个工具。使用最适合特定情况的工具。

在这种情况下,您需要一个 HTML 解析器,例如 BeautifulSoup。

假设您要提取名称(主船员表中的粗体名称):

>>> import requests
>>> from bs4 import BeautifulSoup
>>> url = "http://meridian.puzzlepirates.com/yoweb/crew/info.wm?crewid=5002373"
>>> 
>>> response = requests.get(url)
>>> 
>>> soup = BeautifulSoup(response.content, "html.parser")
>>> table = soup.find('table', width='330')  # relying on width, yeah, does not look reliable
>>> for b in table.find_all('b'):
...     print(b.get_text(strip=True))
... 
Captain
Senior Officer
Fleet Officer
Officer
Pirate
Cabin Person
Jobbing Pirate

【讨论】:

  • 感谢您的帮助,不是 100% 我专门寻找的东西,但 Beautiful Soup 绝对看起来是更强大的工具。我编辑了主要问题并进行了一些澄清。
  • 啊,我找到了解决方案。结果我可以按字体大小搜索并向后计数,因为每次生成的列表的末尾都是相同的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多