北京如何做网站seo短视频入口
一、定义函数获取列表页的内容页地址 get_movie_links()
1、定义列表的地址
2、打开url地址,获取数据
3、解码获取到的数据
4、使用正则得到所有的影片内容也地址
4.1 遍历,取出内容页地址
4.2 拼接内容页地址
4.3 打开内容页地址
4.4 获取数据,并读取
4.5 解码内容页数据,得到html内容页文本
4.6 使用正则,获取下载地址的连接
4.7 把影片信息和下载链接,保存到字典中
4.8 返回字典
二、主函数 main
1、调用 get_movie_list() ,得到字典
2、遍历字典,将内容保存到本地CSV文件中
"""
一、定义函数获取列表页的内容页的地址get_movie_links()
1、定义列表地址https://www.ygdy8.net/html/gndy/dyzz/list_23_1.html
2、打开url1地址,获取数据
3、解码获取到的数据
4、使用正则得到所有影片内容页的地址二、主函数
"""
import urllib.request
import re
import csvdef get_movie_links():# 1、定义列表地址https: // www.ygdy8.net / html / gndy / dyzz / list_23_1.htmlfilm_list_url = "https://www.ygdy8.net/html/gndy/dyzz/list_23_1.html"# 2、打开url1地址,获取数据response_list = urllib.request.urlopen(film_list_url)# 通过read()读取网络资源数据response_list_data = response_list.read()# 3、解码获取到的数据response_list_text = response_list_data.decode("gbk")# 4、使用正则得到所有影片内容页的地址# 使用findall()查找影片内容对应地址url_list = re.findall(r"<a href=\"(.*)\" class=\"ulink\">(.*)</a>", response_list_text)# 定义字典保存电影信息films_dict = {}# 保存地址[('/html/gndy/dyzz/20240514/64980.html', '2024年科幻动作《哥斯拉大战金刚2:帝国崛起》BD中英双字'),……]# 定义变量记录电影条数i = 1# 循环遍历列表得到每个电影的地址for content_url, film_name in url_list:# 拼接目标电影地址content_url = "https://www.ygdy8.net/" + content_url# 打开每一部电影的内容页地址response_content = urllib.request.urlopen(content_url)# 接收内容页的html二进制信息response_content_data = response_content.read()# 解码得到内容页的文本内容response_content_text = response_content_data.decode("gbk")# 取出下载内容页地址# print(response_content_text)result = re.search(r"href=\"(.*?)\"><strong><font style=\"BACKGROUND-COLOR: #ff9966\"><font color=\"#0000ff\">[<font size=\"4\">]*(.*?)</font>",response_content_text)# 将信息保存到字典中films_dict[film_name] = result.group(1)print(f"已经获取{i}条信息")i += 1return films_dictdef main():films_dict = get_movie_links()# 定义CSV文件名csv_file_name = "films.csv"# 打开文件进行写入with open(csv_file_name, 'w', newline='', encoding='utf-8') as csvfile:# 定义CSV文件的列名fieldnames = ['film_name', 'film_link']# 创建csv writer对象writer = csv.DictWriter(csvfile, fieldnames=fieldnames)# 写入列名行writer.writeheader()# 遍历字典并写入数据行for film_name, film_link in films_dict.items():writer.writerow({'film_name': film_name, 'film_link': film_link})print(f"数据已成功保存到当前目录下的{csv_file_name}")if __name__ == '__main__':main()
注意:没有涉及代理,只是对正则表达式的练习应用,可能在爬取过程中被封禁ip,建议设置延时缓慢爬取或自己开启代理 ,否则慎用……