我试图刮掉纬度&本网站的经度编号:
http://www.healthgrades.com/provider-search-directory/search?q=Dentistry&prof.type=provider&search.type=&method=&loc=New+York+City%2C+NY+&pt=40.71455%2C-74.007118&isNeighborhood=&locType=%7Cstate%7Ccity&locIsSolrCity=false
对于每个提供者,如果您查看该元素,它看起来像
div class="listing" data-lat="40.66862" data-lng="-73.98574" data-listing="22"
如何使用beautifulsoup获取纬度和经度数?
我尝试在我的脚本中使用正则表达式,
以下是我的脚本 -
Geo = soup.find("div", class_="providerSearchResults")
print Geo.findAll("div", data-lat_= re.compile('[0-9.]'))
但是我收到此错误消息:" SyntaxError:keyword不能是表达式"
此外,对于每个提供商," div"部分总是变化 它可以是:
div class="listing" data-lat="40.66862" data-lng="-73.98574" data-listing="22"
或
div class="listingfirst" data-lat="40.66862" data-lng="-73.98574" data-listing="22"
甚至
div class="listing enhancedlisting" data-lat="40.66862" data-lng="-73.98574" data-listing="22"
答案 0 :(得分:1)
首先要求:
pip install requests
pip install BeautifulSoup
pip install lxml
<强> latlongbs4.py:强>
import requests
from bs4 import BeautifulSoup
r = requests.get('http://www.healthgrades.com/provider-search-directory/search?q=Dentistry&prof.type=provider&search.type=&method=&loc=New+York+City%2C+NY+&pt=40.71455%2C-74.007118&isNeighborhood=&locType=%7Cstate%7Ccity&locIsSolrCity=false')
soup = BeautifulSoup(r.text, 'lxml')
latlonglist = soup.find_all(attrs={"data-lat": True, "data-lng": True})
for latlong in latlonglist:
print latlong['data-lat'], latlong['data-lng']
编辑: 从attrs词典中删除了class
。
<强>输出:强>
(latlongbs4)macbook:latlongbs4 joeyoung$ python latlongbs4.py
40.71851 -74.00984
40.77536 -73.97707
40.71961 -74.00347
40.71395 -74.008
40.711614 -74.015901
40.724576 -74.001771
40.7175 -74.00087
40.71961 -74.00347
40.71766 -73.99293
40.71961 -74.00347
40.71848 -73.99648
40.709917 -74.009884
40.71553 -74.00977
40.71702 -73.996
40.71254 -73.99994
40.70869 -74.01164
40.70994 -74.00764
40.707325 -74.003982
40.7184 -74.00098
40.71373 -74.00812
40.710474 -74.009844
40.7175 -74.00087
40.727582 -73.894632
40.763469 -73.963106
40.724853 -73.841097
一些注释:
我将attrs
关键字与字典一起使用,因为:
某些属性(如HTML 5中的data- *属性)具有名称 不能用作关键字参数的名称:
您可以通过将这些属性放入搜索中来使用这些属性 字典并将字典传递给find_all()作为attrs 参数:
来源: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-keyword-arguments