【问题标题】:Extracting Content Within Multiple Span Tags in BeautifulSoup在 BeautifulSoup 中提取多个 Span 标签内的内容
【发布时间】: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>

具体来说,我正在尝试提取位于&lt;span class="biz-phone&gt;&lt;/span&gt; 标签之间的电话号码。我尝试使用以下代码:

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

我的问题分为两部分:

  1. 为什么我运行程序时会出现span标签?
  2. 如何摆脱它们?我可以只进行字符串编辑,但我觉得我不会充分利用 BeautifulSoup 包。有没有更优雅的方式?

注意:在整个页面中还有更多类似于上面显示的 HTML 代码的 sn-ps;需要提取更多 &lt;span class="biz-phone"&gt; (555) 123-4567 &lt;/span&gt; 代码实例(即更多电话号码),因此我考虑使用 find_all()

提前谢谢你。

【问题讨论】:

  • 使用phone_numbers.text 甚至phone_numbers.text.strip()
  • 谢谢@furas,成功了!

标签: python html css web-scraping beautifulsoup


【解决方案1】:
  1. find_all() 返回标签列表 (bs4.element.Tag),而不是字符串。

  2. 正如@furas 指出的那样,您希望访问每个标签上的text 属性以提取标签内的文本:

    phone_number_results = [phone_numbers.text.strip() for phone_numbers in soup.find_all('span', 'biz-phone')]

(您可能还想打电话给strip()

【讨论】:

  • 谢谢,.text 成功了!我不知道该属性-我尝试了其他一些属性(即.contents),但这似乎没有帮助。不过,您的解决方案奏效了。
猜你喜欢
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
  • 2012-02-13
相关资源
最近更新 更多