我正在嘗試從書籍網站獲取書籍作者的姓名。我在一列但多行中獲得名稱。我想要一個 csv 單元格中的所有名稱。以下是我的完整代碼
from selenium import webdriver
import pandas as pd
driver = webdriver.Chrome()
site = 'https://www.goodreads.com/book/show/50148349-manto-and-chughtai?from_search=true&from_srp=true&qid=ZARMElvyyt&rank=3'
driver.get(site)
authors = [ ]
names = driver.find_elements_by_xpath('//div[@]')
for name in names:
authors.append(name.find_element_by_xpath('.//a[@]').text)
df = pd.DataFrame({'Author Names': authors})
df.to_csv("Authors_list.csv", index=False)
print(df)
這是我的輸出,我得到了,我想要一個單元格中的所有這四個名稱

uj5u.com熱心網友回復:
你可以試試這個。
authors = ','.join(df['authors'].to_list())
with open('mycsv.csv', 'w', newline='') as myfile:
myfile.write(authors)
uj5u.com熱心網友回復:
我沒有安裝和設定 Selenium 來測驗它。
你能試試這個小調整嗎?
from selenium import webdriver
import pandas as pd
driver = webdriver.Chrome()
site = 'https://www.goodreads.com/book/show/50148349-manto-and-chughtai?from_search=true&from_srp=true&qid=ZARMElvyyt&rank=3'
driver.get(site)
authors = [ ]
names = driver.find_elements_by_xpath('//div[@]')
for name in names:
authors.append(name.find_element_by_xpath('.//a[@]').text)
authors_in_one_cell = ', '.join(authors)
df = pd.DataFrame({'Author Names': authors_in_one_cell})
df.to_csv("Authors_list.csv", index=False)
print(df)
uj5u.com熱心網友回復:
Pandas dataframe.to_csv()方法將從外觀上用換行符寫入每個串列元素。你無意中完成了這個堆疊溢位問題在這里試圖做的事情。
嘗試將作者設定為字串,并將每個新作者附加到該字串而不是串列。只要作者姓名中沒有逗號,在辦公室打開后,所有值都會出現在同一個單元格中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/435275.html
