这是我的代码。
import requests
from bs4 import BeautifulSoup
res = requests.get('http://www.snapdeal.com/products/computers-laptops?sort=plrty&')
soup = BeautifulSoup(res.text)
price = soup.find_all('div', class_="product-price").children
我想从这个网站上抓取数据,但那个 div 没有类,这就是为什么我不知道该怎么做然后我发现你可以找到 div 标签的 child ,但它也不起作用,我'试图获得所有标签。
请您参考如下方法:
有多种方法可以获得所需的价格值。
您可以使用 CSS selector并获得具有 product-price 类的每个 div 的第一个 child :
for price in soup.select("div.product-price > div:nth-of-type(1)"):
print price.get_text(strip=True)
这将打印:
Rs 33490Rs 42990(22%)
Rs 26799Rs 31500(15%)
...
Rs 41790Rs 44990(7%)
Rs 48000Rs 50000(4%)
nth-of-type documentation reference .
请注意,除了实际价格外,它还包含删除线字体上的先前价格。要摆脱它,请使用 find() 和 text=True 仅从 div 获取顶级文本和 recursive=False :
for price in soup.select("div.product-price > div:nth-of-type(1)"):
print price.find(text=True, recursive=False).strip()
打印:
Rs 33490
Rs 26799
...
Rs 41790
Rs 48000
您可以更进一步,省略开头的 Rs 并获取整型(或浮点型)价格值:
for div in soup.select("div.product-price > div:nth-of-type(1)"):
price = div.find(text=True, recursive=False).strip()
price = float(price.replace("Rs ", ""))
print price
打印:
33490.0
26799.0
...
41790.0
48000.0
