爬取豆瓣top100的电影名,时间,演员名,并储存在Excel表格中Python代码xpath方法
时间: 2024-03-31 08:38:26 浏览: 67
豆瓣高分电影爬取项目,思路清晰,易上手代码
好的,使用XPath方法,以下是Python代码:
```python
import requests
from lxml import etree
import openpyxl
# 发送请求并获取网页内容
url = 'https://movie.douban.com/top250'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
html = etree.HTML(response.text)
# 创建Excel表格并添加表头
workbook = openpyxl.Workbook()
worksheet = workbook.active
worksheet.title = 'top100电影'
worksheet['A1'] = '电影名'
worksheet['B1'] = '时间'
worksheet['C1'] = '演员名'
# 获取电影名、时间、演员名,并添加到Excel表格中
for i in range(0, 100, 25):
url = f'https://movie.douban.com/top250?start={i}&filter='
response = requests.get(url, headers=headers)
html = etree.HTML(response.text)
movies = html.xpath('//div[@class="hd"]//span[@class="title"]/text()')
times = html.xpath('//div[@class="bd"]//p[@class=""]/text()')
actors = html.xpath('//div[@class="bd"]//p[@class=""]/text()')
for j in range(25):
movie_name = movies[j]
time = times[j*2+1].strip().replace('\xa0/\xa0', '')
actor = actors[j*2+2].strip().replace('\xa0/\xa0', ', ')
worksheet.append([movie_name, time, actor])
# 保存Excel表格
workbook.save('top100电影.xlsx')
print('保存成功!')
```
这段代码会爬取豆瓣电影Top100的电影名、时间、演员名,并储存到一个名为 `top100电影.xlsx` 的Excel表格中。请注意,我们使用 `lxml` 库的 `etree` 类来解析HTML文档,并使用XPath表达式来选取所需的元素。同样地,为了防止被反爬虫,我们在发送请求时加入了 `User-Agent` 头部信息。
阅读全文