简体   繁体   中英

Python Beautiful Soup parsing error on nested span

I am trying to parse the HTML using python Beautiful Soup.

The part of the HTML is shown below:

<div class="zsg-lg-1-3 zsg-md-1-1 zsg-sm-1-1 value-info-block" id="yui_3_18_1_1_1587802421734_2498">
    <div id="overview" class="scroll-track" data-label="Market Overview"></div>
    <h2 id="yui_3_18_1_1_1587802421734_2509">San Francisco Market Overview</h2>


    <h6 class="zsg-fineprint hdr-date">Data through Mar 31, 2020</h6>
    <ul class="value-info-list" id="yui_3_18_1_1_1587802421734_2497">


        <li id="yui_3_18_1_1_1587802421734_2496">
            <span class="value" id="yui_3_18_1_1_1587802421734_2495">
                $1,310,500
            </span>

            <span class="info zsg-fineprint" id="yui_3_18_1_1_1587802421734_2524"> Median listing price

                <span class="info zsg-fineprint">(Jan&nbsp;31,&nbsp;2020)</span>

            </span>

        </li>

    </ul>

</div>

The python code to extract the HTML is as below:

def process_market_overview(self):
        parent = self.page_soup.find("div", {"data-label": "Market Overview"}).parent
        for li in parent.findAll("li"):
            value = li.find("span", {"class": "value"}, recursive=False).text.strip()
            key = li.find("span", {"class": "info zsg-fineprint"}, recursive=False).text
            key = key[0].strip()
            print(" key :{} , value:{}".format(key, value))

But the output that I am getting is wrong. How do I parse in this kind of scenario? Output is:

key : , value:$1,447,191
 key : , value:-2.3%
 key : , value:$1,310,500
 key : , value:$1,364,300

What I want is to extract the value $1,310,500 and the key Median listing price from the HTML.

URL: https://www.zillow.com/sanfrancisco-ca/home-values/

Let me know if there is any better way of parsing it.

For complete code, you can visit the link: https://github.com/srth12/Eclipse-Workspace-/blob/master/ariya_python_scrapping/zillow_scrapper.py

Use the find method to extract the text from the parent span :

key = li.find("span", {"class": "info zsg-fineprint"})

Not a direct answer, but zillow provides a free api and downloadable csv's with the data that you are trying to scrape:

https://www.zillow.com/research/data/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM