【问题标题】:How to scrape the html data with same kind of tags如何使用相同类型的标签抓取 html 数据
【发布时间】:2014-02-02 15:49:33
【问题描述】:

如何在 python 中使用漂亮的汤提取代理费、卧室和浴室的信息。 [这里][1]是我正在抓取的网页。

<ul class="important-fields">
    <li class="">
        <span> Agency Fees: </span>
        <strong> AED 5000 </strong>
    </li>
    <li class="">
        <span> Bedrooms: </span>
        <strong> Studio </strong>
    </li>
    <li class="">
        <span> Bathrooms: </span>
        <strong> 1 </strong>
    </li>
    <li>
</ul>

【问题讨论】:

  • 我用的是美汤和蟒蛇
    • 代理费: 5000 迪拉姆
    • 卧室: 工作室
    • 浴室: 1
  • 选择或查找全部?请帮忙!!!

标签: python html beautifulsoup


【解决方案1】:
>>> from bs4 import BeautifulSoup
>>> 
>>> html = '''
... <ul class="important-fields">
...     <li class="">
...         <span> Agency Fees: </span>
...         <strong> AED 5000 </strong>
...     </li>
...     <li class="">
...         <span> Bedrooms: </span>
...         <strong> Studio </strong>
...     </li>
...     <li class="">
...         <span> Bathrooms: </span>
...         <strong> 1 </strong>
...     </li>
... </ul>
... '''
>>> 
>>> soup = BeautifulSoup(html)
>>> spans = [x.text.strip() for x in soup.select('ul.important-fields li span')]
>>> strongs = [x.text.strip() for x in soup.select('ul.important-fields li strong')]

>>> spans
[u'Agency Fees:', u'Bedrooms:', u'Bathrooms:']
>>> strongs
[u'AED 5000', u'Studio', u'1']

>>> for name, value in zip(spans, strongs):
...     print('{} {}'.format(name, value))
... 
Agency Fees: AED 5000
Bedrooms: Studio
Bathrooms: 1

【讨论】:

  • 我也做了同样的事情。代码粘贴在下面。问题在于某些字段没有所有标签。例如在某些标签中,代理费缺少 imp_fields=soup.select(".important-fields li strong") for a in imp_fields: info.append(a.get_text().strip().encode("utf-8")) j=0 while j
  • @AhmedMukhtar,你能用显示没有标签的字段的 html 更新你的问题吗?
  • 你太棒了。我稍作修改,它很好地解决了问题。请问这条线是什么意思? print('{} {}'.format(name, value))
  • @AhmedMukhtar,见str.format documentation。它用于字符串插值。
  • 你能帮我在#listing-details-list li span 中获得相同的属性参考和其他标签吗?我正在使用 for a in soup.select("#listing-details-list li span"): print spans_others.append(a.text)
【解决方案2】:

您可以使用 Xpath (http://www.w3schools.com/xpath/) 在 python 中使用 lxml 库从 HTML 中获取数据,您可以在 lxml 教程 (http://lxml.de/tutorial.html) 中找到示例。

【讨论】:

  • 我在用python和美汤
  • 那么我所说的有什么问题? lxml是python中的库,你可以轻松使用它
  • 如何发布一个代码来帮助 OP 使用lxml 解决问题,而不是只提供外部资源的链接?
  • 外部资源可能有更多信息可以从中学习,这些信息可能不会在示例中应用。但是如果我发现资源很难阅读,我可以写一个例子。
猜你喜欢
  • 1970-01-01
  • 2020-10-26
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2019-01-05
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
相关资源
最近更新 更多