2017-05-12 30 views
0

我想從HTML的這部分中提取緯度和經度(有兩對經度/緯度,我需要它可以用於任意數量的座標):使用BeautifulSoup提取經度和緯度(腳本標記)

<script type="text/javascript"> 
[...] 
truvo.data['map']= [{"lat":50.469585,"lon":4.487113,"id":"fr_BE_YP_PAID_16758523_0000_2840991_8600_20139917392","number":"1","display":"1","customerid":"16758523","addressid":"2840991","part":"base","type":"paid"},{"lat":50.721645,"lon":4.6253505,"id":"fr_BE_YP_PAID_12075596_0000_2315340_8600_20139200640","number":"2","display":"2","customerid":"12075596","addressid":"2315340","part":"base","type":"paid"}] 
; 
</script> 

我試了幾種方法:

how to access latitude and longtitude in a script with beautifulsoup?

How to scrape latitude longitude in beautiful soup

和所有其他類型的Ø f stackoverflow提案,但沒有任何工作。

如果我使用一種模式,那一個是正確的嗎?

'("lat"|"lon"):(-?\d{1,3}\.\d+)' 

有人有想法嗎?

非常感謝,

瑪麗

回答

1

你是幾乎沒有,您需要從regex

>>> re.findall(r'("lat"|"lon"):(\d{1,3}\.\d+)', data) 
[('"lat":', '50.469585'), 
('"lon":', '4.487113'), 
('"lat":', '50.721645'), 
('"lon":', '4.6253505')] 

刪除-或者你也可以嘗試(這已經爲你工作)

>>> re.findall(r'(?is)("lat":|"lon":)([0-9.]+)',data) 
+0

非常感謝,它使用腳本完成了一個字符串,但是ho我是否可以用字符串格式的方式從HTML中提取代碼?我通常做soup.find_all('script'),所以目前的格式是bs4.element.Tag – MarieC

+0

使用'str(soup.select('script'))' –

+0

非常感謝,效果很好! – MarieC