python - 如何从我需要的文本中跳过或截断字符或符号。用美丽的汤刮网
问题描述
我需要在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'})
解决方案
这里。您只需要使用该.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'
推荐阅读
- amazon-sqs - Masstransit amazon-sqs 健康检查问题
- c++ - 为什么所有指针都没有被释放?
- javascript - 如何恢复来自 GetStream.io 提要的反应
- python - 使用 PyQt5 更新接口
- swift - 使用 PythonKit 加载 python 文件时遇到问题
- karate - 由于扩展协商错误,空手道 WebSocket 连接失败
- c# - 如何在 ElapsedEvent 期间保持 System.Timers.Timer 停止
- php - PHP在数组的值之间的范围内查找值,然后保存键
- typeerror - 如何解决 TypeError: Can't use a string pattern on bytes-like objects
- python - PerfectSeparationError:检测到完美分离,结果不可用