Python BeautifulSoup 循环
感谢这个论坛,我用这段代码成功获取了我想要的商品名称和价格:
import urllib2
from BeautifulSoup import BeautifulSoup
import re
html = urllib2.urlopen('http://www.toolventure.co.uk/hand-tools/saws/').read()
soup = BeautifulSoup(html)
item = re.sub('\s+', ' ', soup.h2.a.text)
price = soup.find('p', '*price').text
price = re.search('\d+\.\d+', price).group(0)
print item, price
这太棒了,因为它完美地返回了一个结果。接下来,我想获取页面上的所有结果。我一直在尝试使用循环,但我对这个还很陌生,无法弄明白该怎么循环。
有没有人能给我一些指导呢?
非常感谢!
1 个回答
4
我会用 findAll
来处理这个问题:
soup = BeautifulSoup(html)
mostwant = {'class': 'productlist_mostwanted_item '}
griditem = {'class': 'productlist_grid_item '}
divs = soup.findAll(attrs = mostwant) + soup.findAll(attrs = griditem)
for product in divs:
item = product.h2.a.text.strip()
price = re.search('\d+\.\d+', product.findAll('p')[1].text).group(0)
print(f"{item} - {price}")