requests和lxml爬取猫眼电影TOP100

看到他们说使用 xpath 定位元素比较可靠然后自己尝试着修改用正则来提取猫眼电影的数据,话不多说进入正题

导入相关的库

import requests
from requests.exceptions import RequestException
from multiprocessing import Pool
from lxml import etree

尝试着获取页面的内容

def get_one_page(url):
    try:
        headers = {"User-Agent": "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)"}
        response  = requests.get(url=url,headers = headers)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None

加了个简单的异常处理

通过xpath匹配获取需要的内容

def parse_one_page(html):
    tree = etree.HTML(html)
    for num in range(1,11):
        index = ''.join(tree.xpath('//*[@id="app"]/div/div/div[1]/dl/dd[{}]/i/text()'.format(num)))
        title = ''.join(tree.xpath('//*[@id="app"]/div/div/div[1]/dl/dd[{}]/div/div/div[1]/p[1]/a/text()'.format(num)))
        actor =(''.join(tree.xpath('//*[@id="app"]/div/div/div[1]/dl/dd[{}]/div/div/div[1]/p[2]/text()'.format(num)))).strip()
        time = ''.join(tree.xpath('//*[@id="app"]/div/div/div[1]/dl/dd[{}]/div/div/div[1]/p[3]/text()'.format(num)))
        score =''.join(tree.xpath('//*[@id="app"]/div/div/div[1]/dl/dd[{}]/div/div/div[2]/p/i[1]/text()'.format(num))) + ''.join(tree.xpath('//*[@id="app"]/div/div/div[1]/dl/dd[{}]/div/div/div[2]/p/i[2]/text()'.format(num)))
        data = index + ' ' + title + ' ' + actor + ' ' + time + ' ' +score
        write_to_file(data)

因为每页是十部电影的内容 通过循环获取当前页面的所有 排名 电影名字 主演
上映时间 评分 xpath匹配得到的数据是列表类型 我将它转换成字符串类型进行操作 然后将每部电影的内容整合到data中

写入文件

def write_to_file(content):
    with open(r"E:\python\爬虫\data.txt","a",encoding="utf-8") as f:
        f.write(content + '\n')

在parse_one_page这个函数中 每次获取到一个电影的内容将它以追加的形式写入文件

main()

def main(offset):
    url = r"http://maoyan.com/board/4?offset=" + str(offset)
    html = get_one_page(url)
    parse_one_page(html)


if __name__  == "__main__":
    # 1 用循环对其他页面的抓取
    for i in range(10):
        main(10*i)
    # 2 使用进程池加快抓取效率
    # pp = Pool()
    # pp.map(main,[i*10 for i in range(10)])

两种方式对其他页面的抓取

文件中数据的截图
这里写图片描述

欢迎大家对我程序的漏洞提出建议 谢谢

猜你喜欢

转载自blog.csdn.net/xyl180808/article/details/82352946