首页 > 解决方案 > 如何从我需要的文本中跳过或截断字符或符号。用美丽的汤刮网

问题描述

我需要在div标签之间获取价格(61,990),但我怎样才能摆脱货币符号?

在此处输入图像描述

和这里一样,我只需要获取评分(4.7),但在那之后我不需要任何东西,比如img src. 我怎么能忽略它?还是跳过它?

在此处输入图像描述

代码示例:

from bs4 import BeautifulSoup
import requests

price = []
ratings=[]
response = requests.get("https://www.flipkart.com/laptops/~buyback-guarantee-on-laptops-/pr?sid=6bo%2Cb5g&uniq")
soup = BeautifulSoup(response.text, 'html.parser')
for a in soup.findAll('a',href=True, attrs={'class':'_31qSD5'}): 
    price=a.find('div', attrs={'class':'_1vC4OE _2rQ-NK'})
    rating=a.find('div', attrs={'class':'hGSR34'})

标签: pythonpython-3.xweb-scrapingbeautifulsoup

解决方案


这里。您只需要使用该.text方法并将其视为普通字符串即可。在这种情况下,保留除第一个字符之外的所有字符。

from bs4 import BeautifulSoup
import requests

price = []
ratings=[]
response = requests.get("https://www.flipkart.com/laptops/~buyback-guarantee-on-laptops-/pr?sid=6bo%2Cb5g&uniq")
soup = BeautifulSoup(response.text, 'html.parser')
for a in soup.findAll('a',href=True, attrs={'class':'_31qSD5'}):
    price=a.find('div', attrs={'class':'_1vC4OE _2rQ-NK'}).text[1:]
    rating=a.find('div', attrs={'class':'hGSR34'}).text
print(price)
print(rating)
Out[110]: '4.3'
Out[111]: '52,990'

推荐阅读