【问题标题】:unknown error in beautifulsoup web scraping using python使用python进行beautifulsoup web抓取中的未知错误
【发布时间】:2016-06-29 15:12:23
【问题描述】:
<div id="browse_in_widget">
<span id="browse_in_breadcrumb" style="width: 583px;">
<div class="seo_itemscope" itemtype="http://data-vocabulary.org/Breadcrumb" itemscope="">
<a itemprop="url" href="/search/"> Arabian Area</a>
<span class="seo_itemprop-title" itemprop="title">Arabian Area</span>
>
</div>
<div class="seo_itemscope" itemtype="http://data-vocabulary.org/Breadcrumb" itemscope="">
<a itemprop="url" href="/property-for-rent/home/"> Phase 2 </a>
<span class="seo_itemprop-title" itemprop="title">Phase 2 </span>
>
</div>
<div class="seo_itemscope" itemtype="http://data-vocabulary.org/Breadcrumb" itemscope="">
<a itemprop="url" href="/property-for-rent/residential/"> Residential Units for Rent </a>
<span class="seo_itemprop-title" itemprop="title">Residential Units for Rent</span>
>
</div>
<div class="seo_itemscope" itemtype="http://data-vocabulary.org/Breadcrumb" itemscope="">
<a itemprop="url" href="/property-for-rent/residential/apartmentflat/"> Apartment/Flat for Rent </a>
<span class="seo_itemprop-title" itemprop="title">Apartment/Flat for Rent</span>
>
</div>
<strong class="seo_itemprop-title" itemprop="title">Details</strong>
</span>
</div>

我想得到

['Arabian Area', 'Phase 2', 'Residential Units for Rent','Apartment/Flat for Rent']

我正在尝试使用漂亮的 4 python 使用以下代码

try:

        Type = [str(Area.text) for Area in soup.find_all("span", {"class" : "seo_itemscope"})]

        Area=' , '.join(Area)
        print Area


    except StandardError as e:
        Area="Error was {0}".format(e)
        print Area

我想要的只是在列表中获得所需的输出,但似乎存在一些问题。我没有得到任何打印。可能是什么问题?

谢谢!

【问题讨论】:

    标签: python web-scraping beautifulsoup findall


    【解决方案1】:

    第一个问题是您正在寻找不存在的具有seo_itemscope 类的span 元素。如果您要查找标题,请使用seo_itemprop-title

    Type = [item.get_text() for item in soup.find_all("span", {"class": "seo_itemprop-title"})]
    

    另一个问题在这里:

    Area=' , '.join(Area)

    您的意思是加入 Type 列表中的项目:

    Area = ' , '.join(Type)
    

    而且,捕捉StandardError 不是一个好主意——它的异常范围太广,实际上接近于有一个裸露的except 子句。您应该捕获更具体的异常,请参阅:

    【讨论】:

    • 谢谢。如果我只想获取列表中的第四个元素怎么办?即出租公寓/公寓而忽略前三个? python允许吗?
    • @Joanne 当然,你的意思是soup.find_all("span", {"class": "seo_itemprop-title"})[3].get_text()
    • @Joanne 嘿,Joanne - 在这个特定主题中我还有什么可以帮助的吗?如果没有,请考虑将答案标记为已接受以解决该线程。谢谢。
    猜你喜欢
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 2018-09-22
    • 2020-10-04
    • 2015-03-29
    • 2021-01-31
    相关资源
    最近更新 更多