|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import requests
- from bs4 import BeautifulSoup
- import time
- headers = {
- 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
- }
- with open('豆瓣电影排行榜.txt', 'w', encoding='utf-8') as file:
- for page in range(10):
- url = 'https://movie.douban.com/top250?start={}&filter='.format(page*25)
- res = requests.get(url, headers=headers)
- soup = BeautifulSoup(res.text, 'html.parser')
- for item in soup.select('div.item'):
- tag = item.select('div.hd a')
- link = tag[0]['href'] # 地址
- name = tag[0].select('span.title')[0].text # 影片名称
- content = item.select('div.bd p.quote span.inq') # 简介
- score = item.select('div.bd div.star span.rating_num')[0].text # 评分
- number_of_score = item.select('div.bd div.star')[0].text.split()[-1] # 评价人数
- information = item.select('div.bd p')[0].text.split() # 信息列表
- if [y for y in information if y.isdigit()]:
- year = [y for y in information if y.isdigit()][0] + '年' # 上映时间
- else:
- year = '暂无数据'
- if content: # 判断是否为None
- content = content[0].text
- else:
- content = '此影片尚无简介'
- file.write(f'影片名称:《{name}》\n')
- file.write(f'上映时间:{year}\n')
- file.write(f'影片评分:{number_of_score},得分{score}分\n')
- file.write(f'影片简介:{content}\n')
- file.write(f'影片地址:{link}\n')
- file.write('\n')
- print(f'第{page+1}页爬取完毕')
- time.sleep(2)
- else:
- print('done!')
复制代码
初学爬虫,都在拿TOP250的电影练手,我也来试试
在爬取的过程中有部分页面没有数据(比如年份,简介)可能会导致下标越界等错误,要特殊处理。
尝试用了find_all 以及 css选择器方法(目前只会这两种)。发现CSS选择器好用很多。。 |
-
-
|