|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import requests
- from fake_useragent import UserAgent
- url = 'https://movie.douban.com/top250?start=%s&filter='
- ua = UserAgent()
- req = requests.get(url,headers={'User_Agent':str(ua.random)})
- # req.add_header('User_agent',ua)
- response = req.text
- print(response)
复制代码
代码如上,运行没有出错,但是就是打印不出内容,是有什么步骤缺失吗
刚开始学,UA直接网页上复制一个呗
- 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!')
复制代码
|
|