【问题标题】:Parse HTML using Python and Beautiful Soup使用 Python 和 Beautiful Soup 解析 HTML
【发布时间】:2011-09-27 19:16:48
【问题描述】:
<div class="profile-row clearfix"><div class="profile-row-header">Member Since</div><div class="profile-information">January 2010</div></div>
<div class="profile-row clearfix"><div class="profile-row-header">AIGA Chapter</div><div class="profile-information">Alaska</div></div>
<div class="profile-row clearfix"><div class="profile-row-header">Title</div><div class="profile-information">Owner</div></div>
<div class="profile-row clearfix"><div class="profile-row-header">Company</div><div class="profile-information">Mad Dog Graphx</div></div>
我正在使用 Beautiful Soup 在 HTML 代码中达到这一点。我现在想搜索代码,并提取 2010 年 1 月、阿拉斯加、所有者和疯狗图等数据。所有这些数据都具有相同的类,但它们具有不同的变量,例如“Member since”、“AIGA Chapter”等。如何搜索 Member since 并获得 January 2010。对其他 3 个字段执行相同操作?
【问题讨论】:
标签:
python
html
find
beautifulsoup
web-scraping
【解决方案1】:
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup('''<div class="profile-row clearfix"><div class="profile-row-header">Member Since</div><div class="profile-information">January 2010</div></div>
... <div class="profile-row clearfix"><div class="profile-row-header">AIGA Chapter</div><div class="profile-information">Alaska</div></div>
... <div class="profile-row clearfix"><div class="profile-row-header">Title</div><div class="profile-information">Owner</div></div>
... <div class="profile-row clearfix"><div class="profile-row-header">Company</div><div class="profile-information">Mad Dog Graphx</div></div>
... ''')
>>> for row in soup.findAll('div', {'class':'profile-row clearfix'}):
... field, value = row.findAll(text = True)
... print field, value
...
Member Since January 2010
AIGA Chapter Alaska
Title Owner
Company Mad Dog Graphx
你当然可以用field 和value 做任何你想做的事情,比如用它们创建一个字典或将它们存储在数据库中。
如果“profile-row clearfix” div 中有其他 div 或其他文本节点,则需要执行field = row.find('div', {'class':'profile-row-header'}).findAll(text=True) 等操作。
【讨论】:
-
感谢 jcomeau_ictx。如果有类似“
1305 Old Orrville Rd
Selma, AL
"哪里有多个值?