在美丽的div类中查找变量值

时间:2018-08-29 13:14:36

标签: python beautifulsoup

我正在尝试在这段html代码中查找经度和纬度:

<div class="map-outer-wrap">
    <div class="map-wrap" data-zoom="15" style="height:500px;" data-latitude="37.4418834" data-longitude="-122.14301949999998" data-style="color">
        <div data-latitude="37.4418834" data-longitude="-122.14301949999998"></div>
    </div>
    <a href="https://www.google.com/maps/?q=37.4418834,-122.14301949999998&z=10" rel="no-follow" class="overlay-link" target="_blank">View on Google Map</a>
</div>

(整页在这里:https://www.towncity.com/property/whole-hotel-for-sale-in-riverside-area/

我不完全知道从哪里开始实际到达data-latitudedata-longitude,我试图缩小搜索范围以最接近div(map-wrap),但是即使返回一个空列表。

parser = LinkParser()
data, links = parser.getLinks("https://www.towncity.com/property/whole-hotel-for-sale-in-riverside-area/)
lnglat = BeautifulSoup(data, "lxml").findAll("div", {"class": "map-wrap"}).text

在此页面中检索data-latitudedata-longitude的值的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

您可以访问键值对之类的属性

例如:

s = """
<div class="map-outer-wrap">
    <div class="map-wrap" data-zoom="15" style="height:500px;" data-latitude="37.4418834" data-longitude="-122.14301949999998" data-style="color">
        <div data-latitude="37.4418834" data-longitude="-122.14301949999998"></div>
    </div>
    <a href="https://www.google.com/maps/?q=37.4418834,-122.14301949999998&z=10" rel="no-follow" class="overlay-link" target="_blank">View on Google Map</a>
</div>"""


from bs4 import BeautifulSoup


soup = BeautifulSoup(s, "html.parser")
print( soup.find("div", class_="map-wrap")["data-latitude"] )
print( soup.find("div", class_="map-wrap")["data-longitude"] )

输出:

37.4418834
-122.14301949999998

答案 1 :(得分:0)

尝试一下:

from bs4 import BeautifulSoup
import requests

s = requests.get("https://www.towncity.com/property/whole-hotel-for-sale-in-riverside-area/")
soup = BeautifulSoup(s.content, "lxml")
print(soup.find("div", class_="map-wrap")["data-latitude"])
print(soup.find("div", class_="map-wrap")["data-longitude"])

输出:

37.4418834
-122.14301949999998