我一直卡住試圖將我刮到的數據傳輸到一個CSV文件。這裏是我的代碼:寫入抄送數據到csv
import requests, bs4, csv, sys
reload(sys)
sys.setdefaultencoding('utf-8')
url = 'http://www.constructeursdefrance.com/resultat/?dpt=01'
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text,'html.parser')
links = []
for div in soup.select('.link'):
link = div.a.get('href')
links.append(link)
for i in links:
url2 = i
res2 = requests.get(url2)
soup2 = bs4.BeautifulSoup(res2.text, 'html.parser')
for each in soup2.select('li > strong'):
data = each.text, each.next_sibling
with open('french.csv', 'wb') as file:
writer = csv.writer(file)
writer.writerows(data)
輸出說:
Traceback (most recent call last):
File "test_new_project.py", line 23, in <module>
writer.writerows(data)
csv.Error: sequence expected
但我試圖把元組到CSV文件,只要我知道CSV接受元組和列表。我該如何解決這個問題?
是的,它的工作!不知道可以這樣做,減少了學習。你能解釋[each.text,each.next_sibling]在最後一行是如何工作的嗎? – Heavysteps