欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python使用re模塊爬取豆瓣Top250電影

 更新時(shí)間:2020年10月20日 09:40:07   作者:Gg、  
這篇文章主要介紹了python使用re模塊爬取豆瓣Top250電影的示例,幫助大家更好的理解和學(xué)習(xí)python 爬蟲(chóng),感興趣的朋友可以了解下

  爬蟲(chóng)四步原理:

    1.發(fā)送請(qǐng)求:requests

    2.獲取相應(yīng)數(shù)據(jù):對(duì)方及其直接返回

    3.解析并提取想要的數(shù)據(jù):re

    4.保存提取后的數(shù)據(jù):with open()文件處理

  爬蟲(chóng)三步曲:

    1.發(fā)送請(qǐng)求

    2.解析數(shù)據(jù)

    3.保存數(shù)據(jù)

注意:豆瓣網(wǎng)頁(yè)爬蟲(chóng)必須使用請(qǐng)求頭,否則服務(wù)器不予返回?cái)?shù)據(jù)

import re
import requests

# 爬蟲(chóng)三部曲:
# 1.獲取請(qǐng)求
def get_data(url, headers):
  response = requests.get(url, headers=headers)
  # 如果爬取的是html文本就是用.text方法獲取文本數(shù)據(jù),如果爬取的是音視頻就用.content方法獲取二進(jìn)制流數(shù)據(jù)
  # print(response.text)  # 獲取相應(yīng)文本,比如html代碼
  return response.text

# 2.解析數(shù)據(jù)
def parser_data(text):
  # re.findall("正則表達(dá)式", "過(guò)濾的文本", re.S) # 匹配模式:re.S 全局模式
  data = re.findall(
    '<div class="item">.*?<a href="(.*?)" rel="external nofollow" >.*?<span class="title">(.*?)</span>.*?<span class="rating_num" property="v:average">(.*?)</span>.*?<span>(.*?)人評(píng)價(jià)</span>', text, re.S)
  for move_info in data:
    yield move_info

# 3.保存數(shù)據(jù)
def save_data(res_list_iter):
  with open("豆瓣TOP250.txt", "a", encoding="utf-8") as f:
    for i in res_list_iter:
      move_page, move_title, move_score, move_evaluation = i
      # print(move_page, move_title, move_score, move_evaluation)
      str1 = f"電影名字:《{move_title}》  電影評(píng)分:{move_score}  電影評(píng)價(jià):{move_evaluation}  電影詳情頁(yè):{move_page}\n"
      f.write(str1)

# 使用請(qǐng)求頭請(qǐng)求數(shù)據(jù)
headers = {
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 \
  Safari/537.36'
}
n = 0
# 獲取10個(gè)鏈接
for i in range(10):
  url = f"https://movie.douban.com/top250?start={n}&filter=="
  n += 25
  text = get_data(url, headers)
  res_list_iter = parser_data(text)
  save_data(res_list_iter)

  執(zhí)行結(jié)果:

以上就是python使用re模塊爬取豆瓣Top250電影的詳細(xì)內(nèi)容,更多關(guān)于python 爬取豆瓣電影的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論