【发布时间】:2018-06-05 23:32:03
【问题描述】:
我正在使用 BeautifulSoup 解析有关汽车生产的数据(另请参阅我的 first question):
from bs4 import BeautifulSoup
import string
html = """
<h4>Production Capacity (year)</h4>
<div class="profile-area">
Vehicle 1,140,000 units /year
</div>
<h4>Output</h4>
<div class="profile-area">
Vehicle 809,000 units ( 2016 )
</div>
<div class="profile-area">
Vehicle 815,000 units ( 2015 )
</div>
<div class="profile-area">
Vehicle 836,000 units ( 2014 )
</div>
<div class="profile-area">
Vehicle 807,000 units ( 2013 )
</div>
<div class="profile-area">
Vehicle 760,000 units ( 2012 )
</div>
<div class="profile-area">
Vehicle 805,000 units ( 2011 )
</div>
"""
soup = BeautifulSoup(html, 'lxml')
for item in soup.select("div.profile-area"):
produkz = item.text.strip()
produkz = produkz.replace('\n',':')
prev_h4 = str(item.find_previous_sibling('h4'))
if "Models" in prev_h4:
models=produkz
else:
models=""
if "Capacity" in prev_h4:
capacity=produkz
else:
capacity=""
if "( 2015 )" in produkz:
prod15=produkz
else:
prod15=""
if "( 2016 )" in produkz:
prod16=produkz
else:
prod16=""
if "( 2017 )" in produkz:
prod17=produkz
else:
prod17=""
print(models+';'+capacity+';'+prod15+';'+prod16+';'+prod17)
我的问题是,所有匹配的 HTML 事件(“div.profile-area”)的下一个循环会覆盖我的结果:
;Vehicle 1,140,000 units /year;;;;;;
;;;;;;Vehicle 809,000 units ( 2016 );
;;;;;Vehicle 815,000 units ( 2015 );;
;;;;Vehicle 836,000 units ( 2014 );;;
;;;Vehicle 807,000 units ( 2013 );;;;
;;Vehicle 760,000 units ( 2012 );;;;;
;;;;;;;
我想要的结果是:
;Vehicle 1,140,000 units /year;Vehicle 760,000 units ( 2012 );Vehicle 807,000 units ( 2013 );Vehicle 836,000 units ( 2014 );Vehicle 815,000 units ( 2015 );Vehicle 809,000 units ( 2016 );
如果您能告诉我一个更好的方法来构建我的代码,我会很高兴。提前致谢。
【问题讨论】:
-
你想要的结果是什么?
-
我已经更新了我的问题。
-
尝试使用 xPath?我昨天遇到了同样的问题。但我使用了 selenium 和 xPath。所以要解决这个问题,首先抓取 h4 元素,然后遍历每个 //h4 然后在 for 循环 //h4/div[@class="profile-area"]
-
@eddwinpaz 能否请您链接到您的示例(如果它不适合此处)?
-
顺便说一句,使用 pyQuery 比 BeautifulSoup 更容易
标签: python loops beautifulsoup