如何使用BeautifulSoup刮掉缺少标签的网页

时间:2014-08-29 17:18:24

标签: python beautifulsoup

我正在尝试从此页面抓取数据:http://www.kitco.com/texten/texten.html

以下是我正在使用的代码:

import requests
from bs4 import BeautifulSoup

url = "http://www.kitco.com/texten/texten.html"
r = requests.get(url)

# Doing this to force UFT-8 encoding.  Not sure if this is needed...
r.encoding = "UTF-8"

soup = BeautifulSoup(r.content)
tag = soup.find_all("London Fix")
print tag

正如您在查看该页面的来源时会注意到的那样,“伦敦修复”一词不在任何标签中 - 我不确定这是cdata还是什么......

知道如何解析这些表吗?

1 个答案:

答案 0 :(得分:1)

正如@shaktimaan在评论中指出的那样,“伦敦修复”表并不是真实的 - 它位于pre标签内,行使用短划线格式化。

一种选择是在表格前找到font标记并获取.next_sibling

import requests
from bs4 import BeautifulSoup

url = "http://www.kitco.com/texten/texten.html"
r = requests.get(url)

soup = BeautifulSoup(r.content)
print soup.body.pre.find('font', size="4").next_sibling.strip()

打印:

--------------------------------------------------------------------------------
London Fix          GOLD          SILVER       PLATINUM           PALLADIUM
                AM       PM                  AM       PM         AM       PM
--------------------------------------------------------------------------------
Aug 29,2014   1285.75   1285.75   19.4700   1424.00   1424.00   895.00   NA  
Aug 28,2014   1288.00   1292.00   19.7500   1425.00   1428.00   897.00   898.00  
--------------------------------------------------------------------------------
...

另一种选择是按text搜索(产生相同的输出):

import re

print soup.body.pre.find(text=re.compile('London Fix'))
相关问题