【问题标题】:How to scrape ID using Python BeautifulSoup如何使用 Python BeautifulSoup 抓取 ID
【发布时间】:2018-08-15 07:47:03
【问题描述】:

我想在 Python 中使用 BeautifulSoup 抓取 div class= size 和 'ID' 值。

<div class="size ">
 <a class="selectVar" id="23333" data="40593232" data-price="13000,00 €" data-tprice="" data-sh="107-42" data-size-original="92" data-eu="92" data-size-uk="5" data-size-us="5.5" data-size-cm="26.5" data-branch-2="1" data-branch-3="1" data-branch-4="1" data-branch-5="1" data-branch-6="1" data-branch-on="1">
  92
 </a>
</div>

我尝试了以下方法但没有成功:

product = soup.find("div", {'class': 'size ', 'type':'id'})['value']

【问题讨论】:

    标签: python beautifulsoup screen-scraping


    【解决方案1】:

    你在正确的轨道上。
    要获取标签的属性,请使用tag.attrs 方法:

    # Find the <div> tag 
    product_div = soup.find('div', {'class': 'size '})
    
    # Find the <a> tag within the div
    product_tag = product_div.find('a')
    
    # Get the 'id' attribute of the <a> tag
    product_id = product_tag.attrs['id']
    
    print(product_id) # 23333
    

    【讨论】:

    • 谢谢,完美。如果 HTML 中有多个“大小”,我如何打印所有内容,我使用了 soup.find_all 但是我得到 AttributeError: 'ResultSet' object has no attribute 'find'
    • 您需要遍历soup.find_all 返回的标签,例如for product_div in soup.find('div', {'class': 'size '}):
    猜你喜欢
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 2018-06-24
    • 2015-06-07
    • 2014-08-16
    • 1970-01-01
    相关资源
    最近更新 更多