【问题标题】:What do group() and contents[] mean?group() 和 contents[] 是什么意思?
【发布时间】:2013-07-12 01:35:59
【问题描述】:

我正在学习reBeautifulSoup 的模块。我对下一个代码的几行有疑问。我不知道group() 的用途以及contents[] 中括号内的内容是什么

from bs4 import BeautifulSoup
import urllib2
import re

url = 'http://www.ebay.es/itm/LOTE-5-BOTES-CERVEZAARGUS-SET-5-BEER-CANSLOT-5-CANETTES-BIRES-LATTINE-BIRRA-/321162173293'  #raw_input('URL: ')   
code = urllib2.urlopen(url).read();
soup = BeautifulSoup(code)
tag = soup.find('span', id='v4-27').contents[0]

price_string = re.search('(\d+,\d+)', tag).group(1)
precio_final = float(price_string.replace(',' , '.'))

print precio_final

【问题讨论】:

  • 您可以从他们的文档中轻松获得积分。 BeautifulSoupre.

标签: python regex beautifulsoup


【解决方案1】:

.contents 从标签返回项目列表。例如:

>>> from bs4 import BeautifulSoup as BS
>>> soup = BS('<span class="foo"> bar baz <a href="http://foo.com">link</a></span>')
>>> print soup.find('span').contents
[u' bar baz ', <a href="http://foo.com">link</a>]

[0] 用于访问.contents 返回的列表的第一个元素。在上面的例子中,它将返回bar baz

.group(1) 从正则表达式返回第二个(索引从 0 开始,记住)匹配值。查看您的正则表达式,它会返回类似于 n1,n2 的第二个数字。

【讨论】:

    猜你喜欢
    • 2020-07-27
    • 2017-04-13
    • 2011-11-15
    • 1970-01-01
    • 2023-03-08
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多