1 回答
TA贡献1880条经验 获得超4个赞
让我们试试这个:
res = """ <div class="gunDetails">
<h4>Specifications</h4>
<ul class="features">
<li><label>Make:</label><span itemprop="brand">Gamo</span></li>
<li><label>Model:</label><span itemprop="model">Coyote Black Tactical</span></li>
<li><label>Licence:</label><span>No Licence</span></li>
<li><label>Orient.:</label><span>Ambidextrous</span></li>
<li><label>Scope:</label><span>Unknown 3-9x32</span></li>
<li><label>Origin:</label><span>Spanish</span></li>
<li><label>Cased:</label><span>Other</span></li>
<li><label>Trigger:</label><span>1</span></li>
<li><label>Condition:</label><span itemprop="itemCondition">Used</span></li>
</ul>
</div>
""
from bs4 import BeautifulSoup as bs
import csv
labels = []
spans = []
soup = bs(res, 'html.parser')
gun_details = soup.select_one('div.gunDetails')
for l in gun_details.select('label'):
labels.append(l.text.replace(':',''))
for s in gun_details.select('span'):
spans.append(s.text)
my_dict = dict(zip(labels, spans))
with open('mycsvfile.csv','w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=None)
for key in my_dict.keys():
csvfile.write(f"{key},{my_dict[key]}\n")
输出:
Make Gamo
Model Coyote Black Tactical
Licence No Licence
Orient. Ambidextrous
Scope Unknown 3-9x32
Origin Spanish
Cased Other
Trigger 1
Condition Used
添加回答
举报