admin管理员组文章数量:1563235
主要介绍爬取电影天堂首页的电影列表,并将结果保存为csv文件.
1.首先导入需要的模块
import requests
from bs4 import BeautifulSoup
import csv
2.获取网页,并解析结果
def html_parser(url_start):
#获取html
try:
headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'} #模拟浏览器登入
r=requests.get(url_start,headers=headers,timeout=10) #获取网页
except:
pass
#print(r.status_code)
else:
html = r.content.decode('gb2312','ignore') #解码gb2312,忽略其中有异常的编码,仅显示有效的编码
#print(len(html))
#解析网页
soup = BeautifulSoup(html,'lxml')
for li in soup.select('.co_area2 li'): #选择所有class=co_area2 下的所有的 li 节点
for a in li.select('a'): #选择 li 节点下的 a 节点
link=url_start+a['href'] #构造每个电影的网页链接
item={ #将获取的结果存储为字典
"name":a.string,
"link":link
}
save_result(item) #每次获取一个结果后,存储一次
item.clear() #存储后清空字典,为下次存储做准备
因为电影天堂的网页的编码方式是"gb2312",
<META http-equiv=Content-Type content="text/html; charset=gb2312">
<title>电影天堂_免费电影_迅雷电影下载</title>
需要在获取页面的时候,进行解码处理,如下
html = r.content.decode('gb2312','ignore') #解码gb2312,忽略其中有异常的编码,仅显示有效的编码
3.存储结果
def save_result(item): #存储结果
with open('dy.csv','a',newline='',encoding='utf-8') as csvfile: #打开一个csv文件,用于存储
fieldnames=['name','link']
writer=csv.DictWriter(csvfile,fieldnames=fieldnames)
writer.writerow(item)
4.主函数
def main(): #主程序
with open('dy.csv','a',newline='') as csvfile: #写入表头
writer=csv.writer(csvfile)
writer.writerow(['name','link'])
url_start="https://www.dy2018/"
html_parser(url_start)
5.运行
if __name__ == '__main__': #运行主程序
main()
6.运行结果
欢迎关注,获取更多技能
版权声明:本文标题:python 爬取电影天堂电影 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1727487614a1117286.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论