Python Web Scrape - For循环问题

时间:2017-12-14 16:15:22

标签: python html python-3.x web-scraping beautifulsoup

我有这个小项目来网络刮一个网站。我为竞争对手完成了另一个网站,但我现在很难用现在的网站。

代码当前正在做的是创建一个csv文件(这是我想要的),在csv文件中,我显示了标题,但是下面没有数据。

有人可以用我的for循环脚本帮助我。我相信它不会捕获数据以便将其写入csv文件。

感谢您的帮助。

下面是python脚本:

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

# setting my_url to the wesite
urls = ['https://www.extraspace.com/Storage/Facilities/US/North_Carolina/Charlotte/1000000398/Facility.aspx'
    , 'https://www.extraspace.com/Storage/Facilities/US/North_Carolina/Charlotte/1000000404/Facility.aspx']

#https://www.extraspace.com/Storage/Facilities/US/North_Carolina/Charlotte/1000000398/Facility.aspx?cid=org::maps&utm_source=google&utm_medium=organic&utm_campaign=org::maps



filename = "extraspace.csv"
open(filename, 'w').close()
f = open(filename, "a")
num = 0

headers = "unit_size, size_dim1, unit_type, online_price, reg_price, street_address, store_city, store_postalcode\n"

f.write(headers)

for my_url in urls:
    # Opening up connection, grabbing the page
    uClient = uReq(my_url)

    # naming uClient to page_html
    page_html = uClient.read()

    # closing uClient
    uClient.close()

    # this does my html parsing
    page_soup = soup(page_html, "html.parser")

    # setting container to capture where the actual info is using inspect element

    #-----   <div class="right-col-unit-listings" class="unit-listings"> ==$0    -------this is body of each unit container
    #-----   <div class="results"> ==$0    -------this is body of each unit container
    #grabs each product
    containers = page_soup.findAll("div", {"itemprop": "makesOffer"})

    #-----   <div itemprop="address" itemscope itemtype="http://schema.org/PostalAddress"> ==$0     -----this is body of address
    #grabs address
    store_locator = page_soup.findAll("div", {"itemprop": "address"})

    f.write("website " + str(num) + ": \n")
    for container in containers:
        for store_location in store_locator:
            street_address = store_location.findAll("span", {"itemprop": "streetAddress"})
            store_city = store_location.findAll("span", {"itemprop": "addressLocality"})
            store_postalcode = store_location.findAll("spand", {"itemprop": "postalCode"})
            title_container = container.findAll("div", {"class": "size RamaGothicSemiBold"})
            size_dim = container.findAll("div", {"itemprop": "description"})
            #unit_type = container.findAll("ul", {"itemprop": "description"})
            unit_container = container.ul.li
            unit_type = container.text
            online_price = container.findAll("div", {"itemprop": "price"})
            reg_price = container.findAll("div", {"class": "rate strikeout"})

        for item in zip(title_container, size_dim, unit_type, online_price, reg_price, street_address, store_city, store_postalcode):
            csv = item[0].text + "," + item[1].text + "," + item[2] + "," + item[3].text + "," + item[4].text + "," + item[5].text + "," + item[6].text + "," + item[7].text + "\n"
            f.write(csv)
    num += 1

下面是容器的HTML:

<div itemprop="makesOffer" itemscope="" itemtype="http://schema.org/Offer">
    <div itemprop="itemOffered" itemscope="" itemtype="http://schema.org/Product">
        <div class="guide">
            <div class="size-help-lnk size-guide hidden" data-locker="False" data-square-feet="25">Size Help</div>
            <div alt="5x5" class="video-btn-5x5 video-link" onclick="trackSC('UnitListingVideo');"></div>
        </div>
        <div class="size RamaGothicSemiBold">
            <div itemprop="description">5' x 5'</div>
            <div>SMALL</div>
        </div>
        <div class="features">
            <ul itemprop="description">
                <li><i class="check-icon"></i>Enclosed Storage</li>
                <li><i class="check-icon"></i>Indoor</li>
                <li><i class="check-icon"></i>1st Floor Access</li>
            </ul>
        </div>
    </div>
    <div>
        <div class="rate strikeout">
            <div><span style="width:100%;"></span>$57</div><span class="StreetRate">IN-STORE</span></div>
        <div class="rate">
            <div content="35.00" itemprop="price">$35
                <meta content="USD" itemprop="priceCurrency" />
            </div><span class="WebRate">WEB RATE</span></div>
        <div class="promo"><span style="color:#000;">Act fast:<br/>Limited units</span></div>
    </div>
    <a class="btn btn-orange cta-test is-vehicle" href="https://www.extraspace.com/Storage/ReserveOrHold.aspx?uid=a0GC000000tUNupMAG" id="ctl00_mContent_UnitListPopular_ctrl0_hlReserveLink" onclick="upDown('unitRows|8506|1;05X05|NDN|57|35| | ; | | | | | ; | | | | | ;05X05|CDN|71|48| | ;05X07|CDN|74|50| | ');">RESERVE</a>
    <div class="clear"></div>
    <link href="http://schema.org/OnlineOnly" itemprop="availability">
    </link>
</div>

最后是地址的HTML:

< div itemprop = "address"
    itemscope = ""
    itemtype = "http://schema.org/PostalAddress" >
    <span id = "ctl00_mContent_lbAddress"
    itemprop = "streetAddress" > 3304 Eastway Dr < br / > Ste D < /span><br/ >
    <span id = "ctl00_mContent_lbCity"
    itemprop = "addressLocality" > Charlotte < /span>, <
    span id = "ctl00_mContent_lbState"
    itemprop = "addressRegion" > NC < /span> <
    span id = "ctl00_mContent_lbPostalCode"
    itemprop = "postalCode" > 28205 < /span> <
    /div>]

1 个答案:

答案 0 :(得分:0)

网页上只有一个地址,因此您只需要获取一次。所以你可以摆脱其中一个for循环。

中有拼写错误
map_partition

导致None值。

来自zip文档h ttps://docs.python.org/3/library/functions.html#zip

  

当最短输入可迭代用尽时,迭代器停止。

所以它在None值上停止了,你没有得到任何输出。否则,当地址详细信息耗尽时,它会在一次迭代后停止。

修复这些代码的工作原理:

store_postalcode = store_location.findAll("spand", {"itemprop": "postalCode"})

如果您想使用Python csv模块https://docs.python.org/3/library/csv.html

,可以更新它