Python學習筆記

python庫安裝

  • idle:

     **pip install 庫名**
    
  • Pycharm:

在這裏插入圖片描述

1. Requests庫
使用方法:import Requests
主要使用方法:

  • response=requests.get(urlparams={‘wd’:‘python’},headers={“xxx”:“xxx”},timeout=(等待時間,讀取時間))

下面代碼但是自己寫的爬取yande.re圖片網的代碼
首先分析它的圖片地址規律,https://yande.re/post/show/123123,可以知道他是根據右面數字進行下載的。
使用BeautifulSoup分析返回的context,通過find(attrs=“class”:“image”)【找到所有有次屬性的標籤】,return xxx[‘src’],拿到圖片的鏈接。
再請求圖片的鏈接,把返回的二進制content,通過write保存
with open(要保存的圖片地址【包含圖片名稱及後綴】,‘wb’【權限,以二進制形式寫入文件,若存在則覆蓋】) as f
f.write(content)。
到此寫入完成。

在這裏插入圖片描述

from requests.exceptions import RequestException
from requests.exceptions import ConnectTimeout
from requests.exceptions import ReadTimeout
from requests.exceptions import ConnectionError

from urllib.parse import urlencode
from bs4 import BeautifulSoup
import os
import requests
import re
import json
import time
def openurl(url):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36'}
        response = requests.get(url,timeout=(30,15), headers=headers)
        if response.status_code == 200:
            return response
        return None
    except RequestException:
        return None
def searchYandeAndKonSrc(content):
    soup=BeautifulSoup(content, "html.parser")
    soup_list=soup.find(attrs={"class" :"image"})
    return soup_list['src']

# url="https://yande.re/post/show/"+q
# address="E:\CatchPic\test"
# r=openurl("https://yande.re/post/show/3453453")
# url1=searchYandeAndKonSrc(r.content)
# r1=openurl(url1)
# with open("E://CatchPic//test//"+str(q)+".jpg", 'wb') as f:
#     f.write(r1.content)
#     print("保存成功")


q = input("請輸入要從那張開始爬取(倒敘):")
while int(q) > 0:
    try:
        print("第"+str(q)+"張:")
        starttimeshow=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        starttime=time.perf_counter()
        print("開始時間:"+starttimeshow)
        r =openurl("https://yande.re/post/show/"+str(q))
        src = "E://CatchPic//yande1//" + str(q) + ".jpg"
        q = int(q)-1
        url1=searchYandeAndKonSrc(r.content)
        r1=openurl(url1)
        #print(r1.content)
        with open(src, 'wb') as f:
            f.write(r1.content)
            print("保存成功")
        endTimeshow=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        endTime=time.perf_counter()
        print("結束時間:"+endTimeshow)
        print("耗時:"+str(endTime-starttime))
        print("-------------------------------")
    except AttributeError:
        print("第"+str(q)+"張圖片不存在")
    except ReadTimeout:
        print("第"+str(q)+"張圖片,讀取超時")
        time.sleep(5)
    except ConnectionError:
        print("第" + str(q) + "張圖片,地址鏈接失敗")
    except ConnectTimeout:
        print("連接超時")
        time.sleep(60)
    except TypeError:
        print("該連接沒有符合條件的圖片")



  • 百度信息爬取:
  • 思路:首先要訪問https://www.baidu.com/s?wd=xxxx&pn=50,xxx爲所查詢信息,通過pn遍歷沒每一頁(百度的查詢結果每頁pn增加10)。每一個標題都在</h3 class=“t ???”></a href=“xxxx”></a/>標題<//h3>。首先分析標題,通過soup find到h3標籤,拿到它的內容。再獲取h3標籤內的a標籤,再獲取a標籤的href屬性,拿到鏈接。
  • 問題1:
  • 如何拿到標題下的內容簡述?
  • 它的類型有:純文字,圖片加文字,視頻,翻譯,百科等等格式。學習soup標籤遍歷,把各類型的都
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章