Python爬蟲入門

datehoer發表於2020-11-30

什麼是爬蟲?

一段自動抓取網際網路資訊的程式,從網際網路上抓取對於我們有價值的資訊

Python四種基本資料結構

  • 列表

列表中的每個元素都是可變的; 列表的元素都是有序的,也就是說每個元素都有對應的位置; 列表可以容納所有的物件;

list = ['波波', '90, '超哥', '小明']
print(list[0])
print(list(2:))
# result
波波
['超哥', '小明'] # 如果為切片返回的也是列表的資料結構
複製程式碼
  • 字典
user_info = {
  'name': '小明',
  'age': '23',
  'sex': 'male'
}
複製程式碼
  • 元組

在爬蟲中元組和集合很少用到,這裡只做簡單的介紹; 元組: 類似於列表,但是元組的元素是不能修改只能檢視的

# 元組
tuple = (1,2,3)

複製程式碼
  • 集合

集合:類似數學中的集合,每個集合中的元素是無序的,不可以有重複的物件,因此可以通過集合把重複的資料去除!

# 集合
list = [1,1,2,2,3,4,5] 
set = set(list)
# result {1,2,3,4,5}
複製程式碼

Python檔案操作

# 開啟檔案
open(name,[, mode[,buffering]])

f = open('/Users/GreetingText/PycharmProjects/demo/hello.txt')

# 讀寫檔案

f = open('/Users/GreetingText/PycharmProjects/demo/hello.txt', 'w')
f.write('Hello World')

f = open('/Users/GreetingText/PycharmProjects/demo/hello.txt', 'r')
content = f.read()
print(content)
# result Hello World

# 關閉檔案
f.close()
複製程式碼

爬蟲原理

Python爬蟲入門

多頁面爬蟲流程

Python爬蟲入門

如何安裝Python環境?

Mac 系統自帶Python 2.7,安裝 新版本請前往官網下載,安裝成功之後,在命令列輸入python3 如圖:

Python爬蟲入門

工欲善其事,必先利其器

推薦PyCharm

Python爬蟲入門
PyCharm破解方法拿走不謝!

推薦兩個第三方庫

QuickDemo

安裝Scrapy並建立專案

pip install scrapy
scrapy startproject QuickDemo
cd QuickDemo
複製程式碼

在spiders目錄下建立test_spilder.py檔案

Python爬蟲入門

具體程式碼(需要事先安裝BeautifulSoup庫)

# -*- coding:utf-8 -*-
import scrapy
from bs4 import BeautifulSoup


class tsSpride(scrapy.Spider):
    name = 'test' # 爬蟲的唯一名字,在專案中爬蟲名字一定不能重複

    # start_requests() 必須返回一個迭代的Request
    def start_requests(self):
        # 待爬取的URL列表
        urls = ['http://www.jianshu.com/',]
        # 模擬瀏覽器
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
        for url in urls:
            yield scrapy.Request(url=url, headers=headers, callback=self.parse)

    # 處理每個請求的下載響應
    def parse(self, response):
        soup = BeautifulSoup(response.body, 'html.parser')
        titles = soup.find_all('a', 'title')
        for title in titles:
            print(title.string)

        try:
            file = open(r'/Users/GreetingText/QuickDemo/jianshu.txt', 'w')
            # 將爬取到的文章題目寫入txt中
            for title in titles:
                file.write(title.string + '\n')
        finally:
            if file:
                # 關閉檔案(很重要)
                file.close()
複製程式碼

在命令列輸入

scrapy crawl test
複製程式碼

爬取資料成功如圖:

Python爬蟲入門

而且專案裡面也生成了一個jianshu.txt檔案

Python爬蟲入門

開啟jianshu.txt如圖:

Python爬蟲入門

以下是參考連結

本文參考文章

BeautifulSoup官網

Scrapy官網

windows安裝Python3

Mac安裝Python3

相關文章