Python BeautifulSoup解析

2024-09-30 08:20:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取一些内容(对于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、beauthulsoup文档和这个论坛上找到了“现在:£5.95”的代码:

^{pr2}$

但是我想要的结果是5.95。我尝试使用以下链接文本(Spear&Jackson)也取得了有限的成功:

soup.h2.a.contents[0]

当然,这只返回第一个结果。在

我的最终目标是使结果看起来像:

Spear & Jackson Predator Universal Hardpoint Saw - 22 5.95
etc
etc

由于我希望将此导出到csv,我需要弄清楚如何将数据放入两列。就像我说的,我对python非常陌生,所以我希望这是有意义的。在

谢谢你的帮助!在

非常感谢


Tags: 代码div链接h2universalclassspansaw
2条回答

我想你要找的是这样的东西:

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

注意,对于item,正则表达式仅用于删除多余的空白,而对于price则用于捕获数字。在

html = '''
<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">&pound;12.52</span></span><span class="productlist_mostwanted_save">Save: &pound;6.57(52%)</span></p>
<div class="clear"></div>
<p class="productlist_mostwanted_price">Now: &pound;5.95</p>
'''

from BeautifulSoup import BeautifulSoup
import re

soup = BeautifulSoup(html)
desc = soup.h2.a.getText()
price_str = soup.find('p', {"class": "productlist_mostwanted_price" }).getText()
price = float(re.search(r'[0-9.]+', price_str).group())

print desc, price

相关问题 更多 >

    热门问题