Python第三天(spider_豆瓣)

豆瓣top250电影爬虫

import requests
import pandas as pd
from lxml import html
movie_list = []
def spider_douban(page):
    # 获取目标站点的源代码
    url ='https://movie.douban.com/top250?start={}&filter='.format(page)
    # 伪装成浏览器
    headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
        }
   
    response = requests.get(url, headers =headers)
    print(response.status_code)
    html_data = response.text
    # print(html_data)

    # xpath提取
    selector = html.fromstring(html_data)
    # 获取所有电影
    # ul_list = selector.xpath('//div[@class="article"]/ol/li')
    ul_list = selector.xpath('//ol[@class="grid_view"]/li')
    print(len(ul_list))

    # 遍历
    for li in ul_list:
        # 电影序号
        number = li.xpath('.//div[1]/div[1]/em/text()')
        print(number)

        # 电影图片
        picture = li.xpath('.//div[1]/div[1]/a/img/@src')[0]
        print(picture)

        # 电影名
        name = li.xpath('.//div[1]/div[2]/div[1]/a/span[1]/text()')[0]
        print(name)

        #新建img文件夹,存放电影图片,以电影名命名
        image = requests.get(picture)
        with open('./img/'+name+'.png','wb') as f:
            f.write(image.content)

        # 电影信息
        information = li.xpath('.//div[1]/div[2]/div[2]/p/text()')
        # print(type(information))
        # information = information.strip()
        print(information)

        # 评价人数
        people = li.xpath('.//div[1]/div[2]/div[2]/div[1]/span[4]/text()')[0]
        people = people.replace('人评价', ' ')
        people = int(people)
        print(people)

        # 排序
        movie_list.append({
            'name': name,
            'number': number,
            'picture': picture,
            'information': information,
            'people':people
        })
    movie_list.sort(key=lambda x: x['people'], reverse=True)
    for movie in movie_list:
        print(movie)
    # 存储 csv
    df = pd.DataFrame(movie_list)
    df.to_csv('douban250.csv')
#翻页
for page in range(0,250,25):
    spider_douban(page)
# spider_douban(0)

未完待续/...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容