#xpath
#第一種方法 可在開發者工具中找到標簽,右鍵copy xpath,有時需去掉tbody標簽
#第二種方法 簡單學習xpath,自己書寫,掌握基本語法即可,簡單的層級關系

#先將csv文件以記事本打開,更改編碼為ASNI,保存,再用excel打開即可
import urllib.request
import urllib.parse
import csv
from lxml import etree
#需要cmd pip install lxmlheaders = ['電影名字', '評論', '評分', '名句']
with open('C:\\Users\\lenovo\\Desktop\\mmm.csv','a+',newline='', encoding='utf-8') as f:writer = csv.writer(f)writer.writerow(headers)#先將表頭插入
for i in range(10):url ='https://movie.douban.com/top250?start={}&filter='.format(i*25)#發現規律,網址的變化,用format更便捷
response = urllib.request.urlopen(url).read().decode()#源代碼html = etree.HTML(response)#建議學習Xpath,非常有用,web自動化中也會用到
name = html.xpath('//*[@id="content"]/div/div[1]/ol/li/div/div[2]/div[1]/a/span[1]/text()')#電影名字comments = html.xpath('//*[@id="content"]/div/div[1]/ol/li/div/div[2]/div[2]/div/span[4]/text()')#電影評價數star = html.xpath('//*[@id="content"]/div/div[1]/ol/li/div/div[2]/div[2]/div/span[2]/text()')#評分quote = html.xpath('//*[@id="content"]/div/div[1]/ol/li/div/div[2]/div[2]/p[2]/span/text()')#名句
with open('C:\\Users\\lenovo\\Desktop\\mmm.csv','a+',newline='', encoding='utf-8') as f:#將數據寫入csv文件,a+代表繼續寫入writer = csv.writer(f)#將文件對象轉化成csv對象listw = []for i in range(25):listw = [name[i], comments[i], star[i], quote[i]]writer.writerow(listw)#csv按行寫入,寫一個列表
?