使用on将Python输出保存到excel

2024-06-25 06:38:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将Python控制台输出保存到excel文件中。不幸的是,它只保存第一行,但会截断其余的行。你知道吗

html = '''<div class="dynamicBottom">
<div class="dynamicLeft">
<div class="content_block details_block scroll_tabs" data-tab="TABS_DETAILS">
<div class="header_with_improve wrap">
<a href="/UpdateListing.html" onclick="ta.setEvtCookie('UpdateListing', 'entry-detail-moreinfo', null, 0, '/UpdateListingRedesign')"><div class="improve_listing_btn ui_button primary small">improve this entry</div></a>
<h3 class="tabs_header">Details</h3> </div>
<div class="details_tab">
<div class="table_section">
<div class="row">
<div class="ratingSummary wrap">
<div class="histogramCommon bubbleHistogram wrap">
<div class="colTitle">
Rating
</div>
<ul class="barChart">
<li>
<div class="ratingRow wrap">
<div class="label part ">
<span class="text">Location</span>
</div>
<div class="wrap row part ">
<span class="rate sprite-rating_s rating_s"> <img class="sprite-rating_s_fill rating_s_fill s45" src="https://static.tacdn.com/img2/x.gif" alt="45 out of fifty points">
</span>
</div>
</div>
<div class="ratingRow wrap">
<div class="label part ">
<span class="text">Service</span>
</div>
<div class="wrap row part ">
<span class="rate sprite-rating_s rating_s"> <img class="sprite-rating_s_fill rating_s_fill s45" src="https://static.tacdn.com/img2/x.gif" alt="45 out of fifty points">
</span>
</div>
</div>
</li>'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
for div in soup.find_all('div', class_="ratingRow wrap"):
    text = div.text.strip()
    alt = div.find('img').get('alt')
    print(text, alt)

它给出: 位置45/50点 50分中45分

我尝试将此保存到excel,添加最后两行:

for div in soup.find_all('div', class_="ratingRow wrap"):
        text = div.text.strip()
        alt = div.find('img').get('alt')
        print(text, alt)
        worksheet.write_string(row, col+15, text)
        worksheet.write_string(row, col+16, alt)

但这只保存了“位置;50分中的45分”。我想用一行不同的列将输出中给出的信息保存到excel。我有办法做到吗? 非常感谢你的帮助!你知道吗


Tags: textdivimgfindaltexcelfillclass