python爬虫填坑

正式开始填坑了。

昨天上了一上午的课,加上期末复习,每天的计划都要看情况减半。主要就看完,并实现理解了

Python爬虫(3):爬取豆瓣电影TOP250

文章中用的应该是python2语言,自己用的是python3.6版本,中间运行的时候出现一些小问题,百度解决了,不一一详述,仅贴上代码。

# 爬取豆瓣电影TOP250
# coding:utf-8
import requests
from lxml import html

k = 1
# 请求网页内容
# 获取分页
for i in range(10):
    url = 'https://movie.douban.com/top250?start={}&filter='.format(i * 25)
    r = requests.get(url).content
    sel = html.fromstring(r)
    link=sel.xpath('//div[@class="info"]')

    # 提取信息
    for i in link:
        # 影片名称
        title = i.xpath('div[@class="hd"]/a/span[@class="title"]/text()')[0]
        info = i.xpath('div[@class="bd"]/p[1]/text()')
        # 导演演员信息
        info_1 = info[0].replace(" ", "").replace("\n", "")
        # 上映日期
        date = info[1].replace(" ", "").replace("\n", "").split("/")[0]
        # 制片国家
        country = info[1].replace(" ", "").replace("\n", "").split("/")[1]
        # 影片类型
        geners = info[1].replace(" ", "").replace("\n", "").split("/")[2]
        # 评分
        rate = i.xpath('//span[@class="rating_num"]/text()')[0]
        # 评论人数
        comCount = i.xpath('//div[@class="star"]/span[4]/text()')[0]

        print("TOP%s" % str(k))
        print(title, info_1, rate, date, country, geners, comCount)

        # 保存文件
        with open("TOP250.txt", "a", encoding='utf-8') as f:
            f.write("TOP%s\n影片名称:%s\n评分:%s %s\n上映日期:%s\n上映国家:%s\n%s\n" % (k, title, rate, comCount, date, country, info_1 ))
            f.write("=========================================\n")

        k += 1


实验结果



猜你喜欢

转载自blog.csdn.net/jesmine_gu/article/details/80780769