# -*- coding:utf-8 -*-
# @time:2025/7/9 9:50
# @author:张旭辉
# @file : 1-获取全国城市.py
# @编辑器: PyCharm
import time # 时间
import random # 随机数
import re # 正则表达式 一套规则 用于匹配符号条件的记录
from lxml import etree # 从lxml中导入etree 目的是为了解析网页源码
# 从myhttp.py文件中 导入模块 具体 函数是get_data
from myhttp import get_data
# 准备url 1 就是喜剧片的类型 第1页 2 3
for i in range(0,21):
url = f"https://www.dytt8899.com/{i}/index.html"
print(url)
# 发送请求
response = get_data(url)
# 获取数据
# 加载源码
html = etree.HTML(response.text)
# xpath解析
# 获取当前类型电影的最大页码 类型转成int
pagemax = int(html.xpath("//select/option[last()]/text()")[0].split(" ")[1])
for page in range(1,pagemax+1):
# time.sleep(random.randint(1,10))# 睡觉 单位秒 随机范围1-10秒
if page == 1:
url = f"https://www.dytt8899.com/{i}/index.html"
else:
url = f"https://www.dytt8899.com/{i}/index_{page}.html"
# 再次发送请求
# 发送请求
response = get_data(url)
# 获取数据
# 加载源码
html = etree.HTML(response.text)
# 从第page页中取电影类型
type = ''.join(re.findall(r'[\u4e00-\u9fa5]+', html.xpath("//h1//font/text()")[0]))
# 当前页的全部电影数据30条
tables = html.xpath("//div[@class='co_content8']/ul//table")
print(f"============================正在下载【{type}】第{page}/{pagemax}页数据================================")
with open(f"data/{type}.txt","a",encoding="utf-8") as f:
f.write(f"\n---------------------------------{page}/{pagemax}-----------------------------------------\n")
for table in tables:
date = table.xpath(".//tr[3]/td[2]/font[1]/text()")[0] # 日期
score = table.xpath(".//tr[3]/td[2]/font[2]/text()")[0] # 评分
score = re.sub(r'\s+', ' ', score).strip() # 去了回车换行空格之后的评分
title_director = table.xpath(".//tr[4]/td[1]/p[1]/text()")[0] # 片名 导演
title_director = re.sub(r'\s+', ' ', title_director).strip() # 去了回车换行空格之后的 片名 导演
print(date,score,title_director) # 打印
f.write(f"{date} {score} {title_director}\n") # 写入文件
f.write(f"\n---------------------------------{page}-----------------------------------------\n")
print(f"============================【{type}】第{page}/{pagemax}页数据下载完成================================")
print(f"{type}下载完成")
版权属于:
公子初心
作品采用:
《
署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
》许可协议授权
评论 (0)