我正在尝试抓取一些内容(我对 Python 很陌生),但遇到了绊脚石。我要抓取的代码是:
<h2><a href="/best-sellers/sj-b9822.html">Spear & Jackson Predator Universal Hardpoint Saw - 22"</a></h2>
<p><span class="productlist_mostwanted_rrp">
Was: <span class="strikethrough">£12.52</span></span><span class="productlist_mostwanted_save">Save: £6.57(52%)</span></p>
<div class="clear"></div>
<p class="productlist_mostwanted_price">Now: £5.95</p>
我想抓取的是链接文本(Spear & Jackson 等)和价格(5.95 英镑)。我在 Google、BeautifulSoup 文档和这个论坛上查看过,我设法使用以下代码提取“现在:£5.95”:
for node in soup.findAll('p', { "class" : "productlist_grid_price" }):
print ''.join(node.findAll(text=True))
然而我想要的结果只有 5.95。我在尝试使用以下方法获取链接文本 (Spear & Jackson) 时也取得了有限的成功:
soup.h2.a.contents[0]
当然,这只会返回第一个结果。
我的最终目标是让结果看起来像这样:
Spear & Jackson Predator Universal Hardpoint Saw - 22 5.95
etc
etc
由于我希望将其导出到 csv,我需要弄清楚如何将数据放入 2 列中。就像我说的那样,我对 Python 很陌生,所以我希望这是有道理的。
感谢您的帮助!
非常感谢
请您参考如下方法:
我想你要找的是这样的:
from BeautifulSoup import BeautifulSoup
import re
soup = BeautifulSoup(open('prueba.html').read())
item = re.sub('\s+', ' ', soup.h2.a.text)
price = soup.find('p', {'class': 'productlist_mostwanted_price'}).text
price = re.search('\d+\.\d+', price).group(0)
print item, price
示例输出:
Spear & Jackson Predator Universal Hardpoint Saw - 22" 5.95
请注意,对于商品,正则表达式仅用于删除多余的空格,而对于价格,则用于捕获数字。
