Python实现爬取电影天堂最新电影资源

第一次使用爬虫,在这里把踩过的坑细数给大家。如果你像我一样是初次使用,可以借鉴我的代码。

1.导入模块,本次使用到的模块有request,BeautifulSoup

import requests
from bs4 import BeautifulSoup

2.动手干活,我使用的IDE是pycharm,具体的代码如下,过程我都加了注释,如果不懂的话,欢迎留言。

def dytt_reptile(data):
    res.encoding = 'gb2312'    #原网页编码
    soup = BeautifulSoup(res.text, 'html.parser')    #解析获取的html网页

    for title in soup.select('b'):    #在网页源码中寻找关键字
        if len(title)>0:
            try:
                ct = title.select('a')[0].text    #在原网站第27页有一部电影的页面源码不同于其他电影的页面
            except:
                ct = title.select('a')    
            if len(ct) > 0:
                url = 'http://www.dytt8.net' + title.select('a')[0]['href']
                res2 = requests.get(url)
                res2.encoding = 'gb2312'
                soup2 = BeautifulSoup(res2.text, 'html.parser')
                for ul in soup2.select('.co_content8'):
                    url2 = ul.select('a')[0].text
                    if len(url2)> 9:
                        true_url = url2
                        with open('C:\\Users\\Kellen-PC\\Desktop\\test.txt', 'a',encoding='utf-8') as f:#你需要储存文件的路径
                            f.writelines(true_url)
                            f.writelines('\n')
                        print(true_url)

for i in range(1,174):
    if i ==1:
        res = requests.get('http://www.dytt8.net/html/gndy/dyzz/index.html')
        dytt_reptile(res)
    else:
        res = requests.get('http://www.dytt8.net/html/gndy/dyzz/list_23_' + str(i) + '.html')
        dytt_reptile(res)
3.之后获取到的下载链接就已经分行存放到test.txt当中了,用ctrl+f即可搜索需要的电影。

猜你喜欢

转载自blog.csdn.net/qq_39506912/article/details/80116771