【发布时间】:2017-03-13 00:14:30
【问题描述】:
我正在尝试从多个跨度标签中提取字符串内容。 HTML 页面的快照是:
<div class="secondary-attributes">
<span class="neighborhood-str-list">
Southeast
</span>
<address>
1234 Python Blvd S<br>Somewhere, NV 98765
</address>
<span class="biz-phone">
(555) 123-4567
</span>
</div>
具体来说,我正在尝试提取位于<span class="biz-phone></span> 标签之间的电话号码。我尝试使用以下代码:
import requests
from bs4 import BeautifulSoup
res = requests.get(url)
soup = BeautifulSoup(res.text, "html.parser")
phone_number_results = [phone_numbers for phone_numbers in soup.find_all('span','biz-phone')]
编译的代码没有任何语法错误,但它并没有给我想要的结果:
['<span class="biz-phone">\n (702) 476-5050\n </span>', '<span class="biz-phone">\n (702) 253-7296\n </span>', '<
span class="biz-phone">\n (702) 385-7912\n </span>', '<span class="biz-phone">\n (702) 776-7061\n </span>', '<spa
n class="biz-phone">\n (702) 221-7296\n </span>', '<span class="biz-phone">\n (702) 252-7296\n </span>', '<span c
lass="biz-phone">\n (702) 659-9101\n </span>', '<span class="biz-phone">\n (702) 355-9445\n </span>', '<span clas
s="biz-phone">\n (702) 396-3333\n </span>', '<span class="biz-phone">\n (702) 643-9851\n </span>', '<span class="
biz-phone">\n (702) 222-1441\n </span>']
我的问题分为两部分:
- 为什么我运行程序时会出现
span标签? - 如何摆脱它们?我可以只进行字符串编辑,但我觉得我不会充分利用 BeautifulSoup 包。有没有更优雅的方式?
注意:在整个页面中还有更多类似于上面显示的 HTML 代码的 sn-ps;需要提取更多 <span class="biz-phone"> (555) 123-4567 </span> 代码实例(即更多电话号码),因此我考虑使用 find_all()。
提前谢谢你。
【问题讨论】:
-
使用
phone_numbers.text甚至phone_numbers.text.strip() -
谢谢@furas,成功了!
标签: python html css web-scraping beautifulsoup