import urllib.request
from bs4 import BeautifulSoup
import csv
headers = ['部数','章节','链接',]
url = 'http://seputu.com/'
req = urllib.request.Request(url)
res = urllib.request.urlopen(req)
res.encoding = 'utf-8'
html = res.read().decode('utf-8')
soup = BeautifulSoup(html,'html.parser')
rows = []
for mulu in soup.find_all('div',class_='mulu'):
h2 = mulu.find('h2')
if h2!= None:
h2_title = h2.string
for a in soup.find(class_ = 'box').find_all('a'):
href = a.get('href')
title = a['title']
#print(href,title)
rows.append((h2_title,title,href))
print(rows)
with open(r'c:\Users\14547\Desktop\test\testCSV.csv','w') as f:
f_csv = csv.writer(f)
f_csv.writerow(headers)
f_csv.writerows(rows)
这里有个坑,with open(r'c:\Users\14547\Desktop\test\testCSV.csv','w') as f:
这里直接复制的路径总是会报错,后来发现将C盘这里改为小写c就没问题了