import urllib.request
from bs4 import BeautifulSoup
url = "http://movie.douban.com/top250"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'}
targetPath = "storage path"
def saveText(f,text):
f.write(text)
def getData(url,headers):
req = urllib.request.Request(url = url , headers = headers)
res = urllib.request.urlopen(req)
data = res.read()
return data
def praseHtml(f,url,headers):
currenturl = url
i = 1
while currenturl :
html = getData(currenturl,headers)
soup = BeautifulSoup(html,'lxml')
moveList = soup.find('ol',attrs = {'class':'grid_view'})
for moveLi in moveList.find_all('li'):
detail = moveLi.find('div',attrs = {'class':'hd'})
moveName = detail.find('span',attrs = {'class':'title'})
saveText(f,str(i)+ moveName.getText()+'\n')
i += 1
print(moveName.getText())
nextpage = soup.find('span',attrs = {'class':'next'}).find('a')
if nextpage:
currenturl = url + nextpage['href']
else :
currenturl = None
f = open(targetPath,"w")
praseHtml(f,url,headers)