停止以覆盖文本

2024-04-25 16:53:36 发布

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

更新-我通过向数据框添加行,然后只将数据框写入Excel一次,解决了以下问题。其他读者可能会觉得Add one row to pandas DataFrame很有帮助。你知道吗

更新2-如果您想停止将标题名写入Excel,那么您可以找到此帮助How do you remove the column name row from a pandas DataFrame?。你知道吗

更新3-如果您想在将数据框写入Excel时删除行号,那么您可能会发现此链接非常有用Is there any way to remove column and rows numbers from DataFrame.from_dict?。你知道吗

我希望Python从一个Excel文件中读取Amazon url列表(Python.xlsx)然后用URL、产品标题和产品价格填充一个不同的Excel文件(python2.xlsx)。我不想为每个产品创建新的Excel表。我不希望在将新数据写入sheet1时覆盖现有数据。我也不需要使用toexcel命令将标题名和行号写入excel。你知道吗

我查看了How to write to an existing excel file without overwriting data (using pandas)?,但无法将其应用于我的问题。你知道吗

有没有办法阻止将标题名和行号写入Excel?有没有办法阻止电子表格中的现有文本被覆盖?你知道吗

Row = 0
MaxRow = len(df)
while Row <= MaxRow:
    URL = (df.iloc[Row,0]) 
    headers  = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'}
    page = requests.get(URL, headers=headers)
    soup = BeautifulSoup(page.content, 'html.parser')
    title = soup.find(id="productTitle").get_text()
    price = soup.find(id="priceblock_ourprice").get_text()
    converted_price=float(price[1:6])
    df2 = pd.DataFrame({'Url':[URL],
                        'Title':[title.strip()],
                        'Price':[converted_price]})
    writer = ExcelWriter(r'C:\Users\HP\Documents\python2.xlsx')
    df2.to_excel(writer, sheet_name='Sheet1', startrow=Row,startcol=2)
    writer.save()
    Row = Row + 1
    if Row == MaxRow:
        break

Tags: to数据fromurl标题dataframepandasxlsx