爬取豆瓣電影TOP250 增加反爬方法

2021-10-05 21:20:14 字數 1834 閱讀 5483

爬取豆瓣電影top250

網上找的爬蟲例子練手,這好像是最簡單的寫法,不知道是不是年代有點點久遠,例子無法正常執行,後來查才知道是豆瓣加了反爬機制。

所以我就在原基礎上加了反爬方法,做了一點點小改動。因為新接觸python,所以寫法可能不是很好哈哈哈哈哈哈哈哈哈哈哈

# 爬取豆瓣電影top250

import os

import re

import time

import requests

from bs4 import beautifulsoup # 最主要的功能是從網頁抓取資料

def download(url,page):

# 反爬

# user-agent是檢查使用者所用客戶端的種類和版本。通過設定ua可以偽裝成瀏覽器進行訪問目標**

header =

print("正在爬取:")

html = requests.get(url,headers=header)

# 樓上html是requests物件,無法用beautifulsoup解析,可以在後面加上content

soup = beautifulsoup(html.content,'html.parser',from_encoding='utf-8')

lis = soup.select("ol li")

for li in lis:

index = li.find('em').text

title = li.find('span',class_='title').text

rating = li.find('span',class_='rating_num').text

strinfo = re.search("(?<=

).*?(?=<)",str(li.select_one('.bd p')), re.s | re.m).group().strip()

infos = strinfo.split('/')

year = infos[0].strip() # 相當於trim()

area = infos[1].strip()

type = infos[2].strip()

write_fo_file(index, title, rating, year, area, type)

page += 25

if page < 250:

time.sleep(2) # 函式推遲呼叫執行緒的執行 相當於settimeout()

download("",page)

def write_fo_file(index, title, rating, year, area, type):

f = open('d:\move_top250.txt','a',encoding='utf-8')

f.write(' ------ ------ ------ ------ ------ \n')

f.closed

def main():

if os.path.exists("d:\movie_top250.txt"):

os.remove("d:\movie_top250.txt")

f = open('d:\move_top250.txt','w+',encoding='utf-8') # 並從開頭開始編輯,即原有內容會被刪除

write_fo_file("序號","名稱","評分","年份","地區","型別")

url = ""

download(url,0)

print("爬取完畢")

if __name__ == '__main__':

main()

爬取豆瓣電影TOP250

利用css選擇器對電影的資訊進行爬取 import requests import parsel import csv import time import re class cssspider def init self self.headers defget dp self,url respon...

豆瓣Top250電影爬取

from bs4 import beautifulsoup 網頁解析,獲取資料 import re 正規表示式,進行文字匹配 import urllib.request,urllib.error 制定url,獲取網頁資料 import xlwt 進行excel操作 import sqlite3 進行...

python爬取豆瓣電影top250

簡要介紹 爬取豆瓣電影top250上相關電影的資訊,包括影片鏈結 影片名稱 上映時間 排名 豆瓣評分 導演 劇情簡介。使用 requests etree xpath 1 檢視網頁資訊,確定爬取的內容,建立資料庫 class spiderdata peewee.model url peewee.cha...