【问题标题】:BeautifulSoup: Print div's based on content of preceding tagBeautifulSoup:根据前面标签的内容打印 div
【发布时间】:2018-11-08 09:24:38
【问题描述】:

我想根据前面的标签选择元素的内容:

<h4>Models &amp; Products</h4>
    <div class="profile-area">...</div>

<h4>Production Capacity (year)</h4>
    <div class="profile-area">...</div>

如何根据前面标签的内容获取“profile-area”值?

这是我的代码:

import requests
from bs4 import BeautifulSoup
import csv
import re

html_doc = """
<html>
<body>
  <div class="col-md-6">
    <iframe class="factory_detail_google_map" frameborder="0" src=
    "https://www.google.com/maps/embed/v1/search?q=3.037787%2C101.38189&amp;key=AIzaSyCMDADp9QHYbQ8OBGl8puAOv-16W8ziz7Y"
    allowfullscreen=""></iframe>
  </div>

  <div class="col-md-12">
    <h4>Models &amp; Products</h4>

    <div class="profile-area">
      Large Buses, Trucks, Trailer-heads
    </div>

    <h4>Production Capacity (year)</h4>

    <div class="profile-area">
      Vehicle 700 units /year
    </div>

    <h4>Output</h4>

    <div class="profile-area">
      Vehicle 356 units ( 2016 )
    </div>

    <div class="profile-area">
      Vehicle 477 units ( 2015 )
    </div>

    <div class="profile-area">
      Vehicle 760 units ( 2014 )
    </div>

    <div class="profile-area">
      Vehicle 647 units ( 2013 )
    </div>
  </div>
</body>
</html>
"""
soup = BeautifulSoup(html, 'lxml')

#link=soup.iframe.get('src')
#print(link.split("%2C"))

for item in soup.select("div.profile-area"):
    print(item.text)

如您所见,我也在尝试将 Google 地图链接拆分为坐标,但这可能需要我自己解决。

感谢您的帮助!

【问题讨论】:

    标签: python web-scraping beautifulsoup html-parsing coordinates


    【解决方案1】:

    使用.find_previous_sibling() 显式查找前面的第一个h4 标签:

    for item in soup.select("div.profile-area"):
        prev_h4 = item.find_previous_sibling('h4').text
        if 'Capacity' in prev_h4:
            print(item.text)
    

    输出

    Vehicle 700 units /year
    

    【讨论】:

    • 我需要 div 的内容而不是 h4 元素的内容!对于soup.select(“div.profile-area”)中的项目:prev_h4 = str(item.find_previous_sibling('h4'))如果prev_h4中的“容量”:打印(item.text)->为什么它不格式化?一般来说,我想遍历我所有的 HTML 文件。 (我很快就会扩展我的示例脚本。)
    • 很抱歉忘记接受您的回答。你也可以看看stackoverflow.com/questions/50710290/… 吗?
    猜你喜欢
    • 1970-01-01
    • 2012-02-13
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多