我正在尝试使用BeautifulSoup从网站中提取值。这些值基本上是搜索结果,在这种情况下是特定区域的药房。我试图从中提取的页面源包含以下HTML:
<a id="body_BusinessSearchResultSummaryList_repBusinessList_lnkBusinessProfile_1" class="sr-item-link" href="http://www.mocality.co.ke/b/applegene-pharmacy/applegene/brooklyn/health-and-beauty-medical/_/airtime-chemist-cosmetics-medicine/d42f7388-3f9b-4a34-8971-dc6ae9692586?skw=pharmacys&rcnt=10">Applegene Pharmacy</a>
锚标记的id根据结果递增,因此下一个具有2:
<a id="body_BusinessSearchResultSummaryList_repBusinessList_lnkBusinessProfile_2" class="sr-item-link" href="http://www.mocality.co.ke/b/natros-pharmacy/natrosoh/innercore/medical-services/_/_/0cfe6a11-7bee-41f8-8d2e-6a472557201f?skw=pharmacys&rcnt=10">Natros Pharmacy</a>
我已经使用了findAll('a')但是它给了我所有的锚标签。我如何使用BeautifulSoup来解析它并提取特定锚标记的值?
答案 0 :(得分:4)
from BeautifulSoup import BeautifulSoup
txt = '''<a id="body_BusinessSearchResultSummaryList_repBusinessList_lnkBusinessProfile_1" class="sr-item-link" href="http://www.mocality.co.ke/b/natros-pharmacy/natrosoh/innercore/medical-services/_/_/0cfe6a11-7bee-41f8-8d2e-6a472557201f?skw=pharmacys&rcnt=10">Natros Pharmacy</a>
<a id="body_BusinessSearchResultSummaryList_repBusinessList_lnkBusinessProfile_2" class="sr-item-link
" href="http://www.mocality.co.ke/b/natros-pharmacy/natrosoh/innercore/medical-services/_/_/0cfe6a11-
7bee-41f8-8d2e-6a472557201f?skw=pharmacys&rcnt=10">Natros Pharmacy</a>'''
match = 'body_BusinessSearchResultSummaryList_repBusinessList_lnkBusinessProfile'
soup = BeautifulSoup(txt)
for a in soup.findAll('a'):
if a.has_key('id') and a['id'].startswith(match):
print a['href'], a.contents
答案 1 :(得分:0)
使用find
的关键字参数来限制属性:
find("a", id="whatever_1")
您也可以使用(布尔)函数调用find
:
def isRight(tag):
return ...
findAll(isRight)