如何解决BeautifulSoup4,如何获取<td>及其<tr>中的类?
我正在尝试构建一个网络爬虫,但是不确定如何在语法上继续前进。
content = soup.find_all('td',class_ ='serviceListing')
for property in content:
name = property.find('a').text
details = property.find('span').text
Pagelist = {
'Name' : name,'Details' : details
}
serviceList.append(Pagelist)
print(serviceList)
Source Code:
<tr>
<td id = 'xx' class='serviceListing' style='yy: zz;' bgcolor="FFFFFF")
<a id = "content" href="displayService,aspx?id=147674">Location Name</a>
<a href="servicesprovidedinfrench.aspx" class... </a>
<br>
<span id = "content" class='regtext">801 location</span>
</td>
<td valign="top" class='serviceListingCity" ... </td>
<span id="contentplaceholderPhone" class"regtext">905 905 9055 </span>
</td>
<td> ... </td>
我了解我的代码只是获取代码的第一次迭代。返回内的每次迭代的正确语法是什么?
当前,我只能获取“位置名称/ a”和“ span id 801 location / span”?
我将如何在serviceListingCity类中获取td和“ span 905 905 9055 / span”的第二次迭代?
谢谢!
解决方法
我希望我对您的问题理解正确:您想在<td class="serviceListing">
旁边查找信息吗?如果是,则可以执行.find_next()
方法:
from bs4 import BeautifulSoup
html = """
<tr>
<td id="xx" class="serviceListing">
<a id="content" href="displayService,aspx?id=147674">Location Name</a>
<a href="servicesprovidedinFrench.aspx">...</a>
<br>
<span id="content" class="regtext">801 location</span>
</td>
<td valign="top" class="serviceListingCity">
<span id="contentplaceholderPhone" class"regtext">905 905 9055</span>
</td>
<td> ... </td>
</tr>
"""
soup = BeautifulSoup(html,'html.parser')
for prop in soup.select('td.serviceListing'):
name = prop.find('a').text
details = prop.find('span').text
phone = prop.find_next('span',id='contentplaceholderPhone').text
print(name)
print(details)
print(phone)
打印:
Location Name
801 location
905 905 9055
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。