1. 程式人生 > 程式設計 >Python如何使用BeautifulSoup爬取網頁資訊

Python如何使用BeautifulSoup爬取網頁資訊

這篇文章主要介紹了Python如何使用BeautifulSoup爬取網頁資訊,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

簡單爬取網頁資訊的思路一般是

1、檢視網頁原始碼

2、抓取網頁資訊

3、解析網頁內容

4、儲存到檔案

現在使用BeautifulSoup解析庫來爬取刺蝟實習Python崗位薪資情況

一、檢視網頁原始碼

這部分是我們需要的內容,對應的原始碼為:

分析原始碼,可以得知:

1、崗位資訊列表在<section class="widget-job-list">中

2、每條資訊在<article class="widget item">中

3、對於每條資訊,我們需要提取出的內容是 公司名稱,職位, 薪資

二、抓取網頁資訊

使用request.get()抓取,返回的soup是網頁的文字資訊

def get_one_page(url):
  response = requests.get(url)
  soup = BeautifulSoup(response.text,"html.parser")
  return soup

三、解析網頁內容

1、找到起始位置<section>

2、在<article>中匹配到各項資訊

3、返回資訊列表用以儲存

def parse_page(soup):
  #待儲存的資訊列表
  return_list = []
  #起始位置
  grid = soup.find('section',attrs={"class": "widget-job-list"})
  if grid:
    #找到所有的崗位列表
    job_list = soup.find_all('article',attrs={"class": "widget item"})

    #匹配各項內容
    for job in job_list:
      #find()是尋找第一個符合的標籤
      company = job.find('a',attrs={"class": "crop"}).get_text().strip()#返回型別為string,用strip()可以去除空白符,換行符
      title = job.find('code').get_text()
      salary = job.find('span',attrs={"class": "color-3"}).get_text()
      #將資訊存到列表中並返回
      return_list.append(company + " " + title + " " + salary)
  return return_list

四、儲存到檔案

將列表資訊儲存到shixi.csv檔案中

def write_to_file(content):
  #以追加的方式開啟,設定編碼格式防止亂碼
  with open("shixi.csv","a",encoding="gb18030")as f:
    f.write("\n".join(content))

五、爬取多頁資訊

在網頁url中 可以看到最後的page代表的是頁數資訊

所以在main方法中傳入一個page,然後迴圈執行main(page)就可以爬取多頁資訊了

def main(page):
  url = 'https://www.ciweishixi.com/search?key=python&page=' + str(page)
  soup = get_one_page(url)
  return_list = parse_page(soup)
  write_to_file(return_list)
if __name__ == "__main__":
  for i in range(4):
    main(i)

六、執行結果

七、完整程式碼

import requests
import re
from bs4 import BeautifulSoup

def get_one_page(url):
  response = requests.get(url)
  soup = BeautifulSoup(response.text,"html.parser")
  return soup

def parse_page(soup):
  #待儲存的資訊列表
  return_list = []
  #起始位置
  grid = soup.find('section',attrs={"class": "color-3"}).get_text()
      #將資訊存到列表中並返回
      return_list.append(company + " " + title + " " + salary)
  return return_list

def write_to_file(content):
  #以追加的方式開啟,設定編碼格式防止亂碼
  with open("shixi.csv",encoding="gb18030")as f:
    f.write("\n".join(content))
def main(page):
  url = 'https://www.ciweishixi.com/search?key=python&page=' + str(page)
  soup = get_one_page(url)
  return_list = parse_page(soup)
  write_to_file(return_list)
if __name__ == "__main__":
  for i in range(4):
    main(i)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。