我正在用漂亮的汤从这里剪贴数据:https://www.booli.se/annons/1887654
这是我在python 2.7中的代码:
import requests
from bs4 import BeautifulSoup
page="https://www.booli.se/annons/2272818"
request = requests.get(page)
soup = BeautifulSoup(request.text,'lxml')
Int[3]: soup.findAll('span', itemprop='name')[4].text.strip().encode('utf-8')
Out[3]:'3 rum, 67 m\xc2\xb2'
Int[4]:d=soup.findAll('span', class_='property__base-info__value')
Out[4]: [<span class="property__base-info__value">\n\t\t\t17 mar
2017\n\t\t</span>,
<span class="property__base-info__value">\n\t\t\t2 850 000
kr\n\t\t\t<span class="property__base-info__sub-value">42 537
kr/m\xb2</span>\n</span>,
<span class="property__base-info__value">4 921 kr/m\xe5n</span>,
<span class="property__base-info__value">L\xe4genhet</span>,
<span class="property__base-info__value">233 kr/m\xe5n</span>,
<span class="property__base-info__value">3 tr</span>,
<span class="property__base-info__value">1907 </span>]
Int[5]: d[2].text.strip().encode('utf-8')
Out[5]:'4 921 kr/m\xc3\xa5n'
Int[6]: d[1].text.strip().encode('utf-8')
Out[6]: '2 850 000 kr\n\t\t\t42 537 kr/m\xc2\xb2'
现在我的问题是:
Q1:进出[3] --->如何从67 m \ xc2 \ xb2中分离出3个朗姆酒?
Q2:在Out [3] --->如何摆脱朗姆酒和m \ xc2 \ xb2?我只想保存3个房间,而67个房间,例如:
房间面积
3 67
Q3:Out [5] Out [6]同样的问题。我需要删除文本,而只是单独保存值。抱歉,该网页是瑞典语。谢谢。
最佳答案
打印m\xc2\xb2
是因为无法在UTF-8中确定m²
。
如果将soup.findAll('span', itemprop='name')[4].text.strip().encode('utf-8')
更改为soup.findAll('span', itemprop='name')[4].text
它打印3 rum, 67 m²
如果您确信源具有一致的格式,并且只希望数字值,则可以执行以下操作:
import requests
from bs4 import BeautifulSoup
page="https://www.booli.se/annons/2272818"
request = requests.get(page)
soup = BeautifulSoup(request.text,'lxml')
info = {}
a = soup.findAll('span', itemprop='name')[4].text
a = [int(s) for s in a.split() if s.isdigit()]
info['Rooms'] = a[0]
info['Area'] = a[1]
temp = []
date = soup.findAll('span', class_='property__base-info__value')
for i in date:
i = i.text.strip()
temp.append(i)
temp[1] = temp[1].split('\n')[0]
info['Såld'] = temp[0]
info['Utropspris'] = temp[1]
info['Avgift'] = temp[2]
info['Bostadsty'] = temp[3]
info['Driftskostnad'] = temp[4]
info['Våning'] = temp[5]
info['Byggår'] = temp[6]
import pprint
pprint.pprint(info)
关于python - 使用BeautifulSoup获取HTML标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42882869/