How to scrape ID using Python BeautifulSoup

流过昼夜 提交于 2019-12-11 18:36:08

问题


I would like to scrape the div class = size along with 'ID' value using BeautifulSoup in Python.

<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>

I Have tried the following with no success:

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

回答1:


You're on the right track.
To get the attributes of a tag, use the tag.attrs method:

# 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


来源:https://stackoverflow.com/questions/49148003/how-to-scrape-id-using-python-beautifulsoup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!