【问题标题】:Trouble getting items from some messy elements无法从一些杂乱的元素中获取项目
【发布时间】:2018-12-13 07:31:16
【问题描述】:

我已经在 python 中结合BeautifulSoup 编写了一个脚本,以从一些html elements 中抓取addressesaddressesbr 标签分隔,所以我无法使用 next_sibling 获取所有这些标签。我尝试了两种不同的方法来接触它们。但是,后者稍微接近。我仍然不确定获得addresses 的有效方法应该是什么,就像我在预期输出中粘贴的方式一样。提前致谢。

Elements 位于其中的addresses

<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 值,您只需将and item.string 添加到条件中。如果你想去掉所有多余的空格并加入空格,你可以做' '.join(part.strip() for part in part)
  • 通常你可以只使用stripped_strings 来完成大部分工作,但是由于这个HTML 是一团糟,没有div 或其他结构甚至布局标签来保存地址而没有其他无关紧要的东西,没有办法有点乱。
  • 这不是一种解决方法,而是建议使用addr = [item.string for item in items.children if not item.name=="a"]addr 获取相同的输出(不那么痛苦)。

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

看起来你只需要更新你的列表理解来解释空格和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'

【讨论】:

  • 我多次尝试执行您建议的部分,但遇到此错误:addr = [strip(item.string) for item in items.select_one("h4").next_siblings if item and not item.name=="a"] NameError: name 'strip' is not defined
  • 哎呀,对不起!更新了!
  • 对不起,亲爱的,你不能这样做我的意思是,你不能在发电机上申请.strip()。这不是一个有效的方法。还是谢谢。
  • 好的,亲爱的。但是,item.string 不是生成器,它是str,是的,您可以在生成器中应用它们。为什么你不能?上面的代码对我有用。
  • 现在它就像一个魅力。 if item.string 成功了。接受并赞成。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2019-05-08
  • 2018-02-14
  • 2019-12-27
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多