首先我需要给一个请求头
U
s
e
r
−
A
g
e
n
t
User-Agent
User−Agent
获取方式为:
``右键鼠标,会弹出如下所示的内容,选择最后一个检查,便可得出该网页的源代码。
首先点击右上方出现的网络按钮,刷新页面,随机点进去一个请求,如下图所示。
直接复制上述内容,就可获得请求头。
下面利用Xpath来进行爬取
我们运用由上面的快捷标志,选取我们要爬取的单元块,可以快速定位到所在代码位置
选中,点击右键,会出现上述内容,选择复制,复制Xpath就可以。
具体的获取方式与这个操作相同,下面是爬取的整个过程。
# 导入模块
import requests # 网络请求模块
from lxml import etree # 数据解析模块
import pandas as pd
# 请求头信息
headers = {
'User-Agent':
''
}
# 定义函数
def get_first_text(list):
try:
return list[0].strip()
except:
return ""
df = pd.DataFrame(columns=["序号", "标题", "链接", "导演", "评分", "评价人数", "简介"])
# 使用列表生成式表示10个页面的地址
urls = ["https://movie.douban.com/top250?start={}&filter=".format(str(i * 25)) for i in range(10)]
count = 1 # 计数
for url in urls:
res = requests.get(url=url, headers=headers) # 发起请求
html = etree.HTML(res.text) # 将返回的文本加工为可以解析的html
lis = html.xpath('//*[@id="content"]/div/div[1]/ol/li') # 获取每个电影的li元素
# 解析数据
for li in lis:
title = get_first_text(li.xpath('./div/div[2]/div[1]/a/span[1]/text()')) # 电影标题
scr = get_first_text(li.xpath('./div/div[2]/div[1]/a/@href')) # 电影链接
dictor = get_first_text(li.xpath('./div/div[2]/div[2]/p[1]/text()')) # 导演
score = get_first_text(li.xpath('./div/div[2]/div[2]/div/span[2]/text()')) # 评分
comment = get_first_text(li.xpath('./div/div[2]/div[2]/div/span[4]/text()')) # 评价人数
summary = get_first_text(li.xpath('./div/div[2]/div[2]/p[2]/span/text()')) # 电影简介
print(count, title, scr, dictor, score, comment, summary) # 输出
df.loc[len(df.index)] = [count, title, scr, dictor, score, comment, summary]
count += 1
df.to_excel("豆瓣电影top250数据.xlsx", sheet_name="豆瓣电影top250数据", na_rep="")
print("保存完成")