怎么用python抓取豆瓣上用户对电影的评分

 我来答
js...e@163.com
2017-11-07 · 超过100用户采纳过TA的回答
知道小有建树答主
回答量:174
采纳率:40%
帮助的人:133万
展开全部
#!/usr/bin/env python2.7# encoding=utf-8"""
爬取豆瓣电影TOP250 - 完整示例代码
"""import codecsimport requestsfrom bs4 import BeautifulSoup

DOWNLOAD_URL = 'http://movie.douban.com/top250/'def download_page(url):
return requests.get(url, headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'
}).contentdef parse_html(html):
soup = BeautifulSoup(html)
movie_list_soup = soup.find('ol', attrs={'class': 'grid_view'})

movie_name_list = [] for movie_li in movie_list_soup.find_all('li'):
detail = movie_li.find('div', attrs={'class': 'hd'})
movie_name = detail.find('span', attrs={'class': 'title'}).getText()

movie_name_list.append(movie_name)

next_page = soup.find('span', attrs={'class': 'next'}).find('a') if next_page: return movie_name_list, DOWNLOAD_URL + next_page['href'] return movie_name_list, Nonedef main():
url = DOWNLOAD_URL with codecs.open('movies', 'wb', encoding='utf-8') as fp: while url:
html = download_page(url)
movies, url = parse_html(html)
fp.write(u'{movies}\n'.format(movies='\n'.join(movies)))if __name__ == '__main__':
main()
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式