gpt4 book ai didi

python - 从一些杂乱的元素中获取元素时遇到问题

转载 作者:行者123 更新时间:2023-11-30 22:15:34 25 4
gpt4 key购买 nike

我用 python 结合 BeautifulSoup 编写了一个脚本,用于从一些 html 元素 中抓取地址地址br标签分隔,因此我无法使用next_sibling获取所有地址。我尝试过两种不同的方法来达到它们。不过,后者稍微接近一些。我仍然不确定获取地址的有效方法应该是什么,就像我在预期输出中粘贴的方式一样。提前致谢。

地址所在的

元素:

<div class="item-listing">
<h4><a href="/alps/" target="_blank">AK</a></h4>
5200 A St Ste 102<br>
Anchorage, AK 99518<br>

Phone: (907) 563-9333
<br>
<ul class="list-items" style="margin-top: 5px;">
<li style="padding: 3px; background: #efefef; border-radius: 4px;"><img src="/images/icon-rec.png" style="height: 24px; width: 24px;" alt="Rl" data-toggle="tooltip" data-placement="top" title="Sales"></li>
</ul>
<a style="margin-right: 10px;" href="http://www.alps.com/?" target="_blank">Website</a>
<a href="/al/anchorage/" target="_blank">Profile</a>
</div>

到目前为止我已经尝试过:

soup = BeautifulSoup(content,"lxml") #here content holding the elements above
for items in soup.select(".item-listing"):
addr = [item.next_sibling for item in items.select("h4")]
# addr = [item.string for item in items.select_one("h4").next_siblings if not item.name=="a"]
print(addr)

第一个 addr 的结果(来自脚本):

['\n    5200 A St Ste 102']

注释掉addr的结果:

['\n    5200 A St Ste 102', None, '\n    Anchorage, AK 99518', None, '\n        \n    Phone: (907) 563-9333\n    ', None, '\n', None, '\n', '\n', '\n']

我的预期输出(或非常接近于此):

5200 A St Ste 102 Anchorage, AK 99518 Phone: (907) 563-9333

最佳答案

看起来您只需要更新列表理解即可解决空格和 None 值。

试试这个:

addr = [item.string.strip() for item in items.select_one("h4").next_siblings if item and item.string and not item.name=="a"]`

使用 item.string.strip() 将消除多余的空格和 \n。添加 if item 将过滤掉 None 值。

这应该会导致

['5200 A St Ste 102', 'Anchorage, AK 99518', 'Phone: (907) 563-9333']

您可以加入不为空的元素:

' '.join([a for a in addr if a])

这将导致

'5200 A St Ste 102 Anchorage, AK 99518 Phone: (907) 563-9333'

关于python - 从一些杂乱的元素中获取元素时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50256912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com