张树袋 发表于 2020-7-24 15:57:18

朕想知道

weiyideid823 发表于 2020-7-24 16:02:04

朕想知道

教程表 发表于 2020-7-25 09:26:11

朕想知道

鲜格格 发表于 2020-7-25 23:36:57

朕想知道

lslslsls12 发表于 2020-7-27 16:29:05

1

syman0203 发表于 2020-7-27 16:50:47

小白,刚接触,要好好学习鸭

penut' 发表于 2020-7-27 18:54:55

1

jack_xy 发表于 2020-7-28 07:53:43

朕想知道

aa757818537 发表于 2020-7-28 14:09:35

1

能坚持几天 发表于 2020-7-28 16:44:13

朕想知道

hudayun 发表于 2020-7-28 20:18:10

支持小甲鱼

彻彻底底 发表于 2020-7-29 12:36:34

1

红蓝cp 发表于 2020-7-29 13:37:44

。。。

fengahao 发表于 2020-7-29 14:15:40

朕想知道

吾深知秋 发表于 2020-7-29 18:53:33

朕想知道

邱小冬 发表于 2020-7-30 17:04:23

{:5_90:}

温木zou 发表于 2020-7-31 11:48:50

giao

爱笑的皮卡媛 发表于 2020-8-2 16:44:28

lalala

aaron.yang 发表于 2020-8-2 18:59:24


联想知道

反清复明君 发表于 2020-8-3 11:37:14

import requests
import bs4
import re
import openpyxl

def open_url(url):
    # 使用代理
    # proxies = {"http": "127.0.0.1:1080", "https": "127.0.0.1:1080"}
    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36'}

    # res = requests.get(url, headers=headers, proxies=proxies)
    res = requests.get(url, headers=headers)

    return res

def find_movies(res):
    soup = bs4.BeautifulSoup(res.text, 'html.parser')

    # 电影名
    movies = []
    targets = soup.find_all("div", class_="hd")
    for each in targets:
      movies.append(each.a.span.text)

    # 评分
    ranks = []
    targets = soup.find_all("span", class_="rating_num")
    for each in targets:
      ranks.append(each.text)

    # 资料
    messages = []
    targets = soup.find_all("div", class_="bd")
    for each in targets:
      try:
            messages.append(each.p.text.split('\n').strip() + each.p.text.split('\n').strip())
      except:
            continue

    result = []
    length = len(movies)
    for i in range(length):
      result.append(, ranks, messages])

    return result

# 找出一共有多少个页面
def find_depth(res):
    soup = bs4.BeautifulSoup(res.text, 'html.parser')
    depth = soup.find('span', class_='next').previous_sibling.previous_sibling.text

    return int(depth)

def save_to_excel(result):
    wb = openpyxl.Workbook()
    ws = wb.active

    ws['A1'] = "电影名称"
    ws['B1'] = "评分"
    ws['C1'] = "资料"

    for each in result:
      ws.append(each)

    wb.save("豆瓣TOP250电影.xlsx")

def main():
    host = "https://movie.douban.com/top250"
    res = open_url(host)
    depth = find_depth(res)

    result = []
    for i in range(depth):
      url = host + '/?start=' + str(25 * i)
      res = open_url(url)
      result.extend(find_movies(res))

    '''
    with open("test.txt", "w", encoding="utf-8") as f:
      for each in result:
            f.write(each)
    '''

    save_to_excel(result)
   
if __name__ == "__main__":
    main()
页: 31 32 33 34 35 36 37 38 39 40 [41] 42 43 44 45 46 47 48 49 50
查看完整版本: 使用Python读写Excel文件(1)