1. 程式人生 > >爬蟲入門教程之requests,BeautifulSoup庫的介紹以及問題解釋

爬蟲入門教程之requests,BeautifulSoup庫的介紹以及問題解釋

 

HTTP協議

HTTP,超文字傳輸協議(HTTP,HyperText Transfer Protocol)是網際網路上應用最為廣泛的一種網路協議。所有的WWW檔案都必須遵守這個標準。設計HTTP最初的目的是為了提供一種釋出和接收HTML頁面的方法,HTTP是一種基於"請求與響應"模式的、無狀態的應用層協議。HTTP協議採用URL作為定位網路資源的的識別符號。
http://host[:post][path]
host:合法的Internet主機域名或ip地址
port:埠號,預設為80
path:請求資源的路徑

HTTP URl的理解:
url是通過HTTP協議存取資源的的Internet路徑,一個URL對應一個數據資源。
 

Requests庫

與HTTP協議操作相對應的requests庫的7個方法如下:

方法 說明
requests.request() 構造一個請求,支撐以下各方法的基礎方法
requests.get() 獲取HTML網頁的主要方法,對應於HTTP的GET
requests.head() 獲取HTML網頁頭資訊的方法,對應於HTTP的HEAD
requests.post() 向HTML網頁提交POST請求的方法,對應於HTTP的POST
requests.put() 向HTML網頁提交PUT請求的方法,對應於HTTP的PUT
requests.patch() 向HTML網頁提交區域性修改請求,對應於HTTP的PATCH
requests.delete() 向HTML頁面提交刪除請求,對應於HTTP的DELETE

 

 

 

 

 

 

 

 

 

安裝

pip install requests

requests庫安裝小測

import request
url = 'https://www.baidu.com'
r = requests.get(url)
r.encoding = r.apparent_encoding
print(r.text[-200:])

Out[13]: 'w.baidu.com/duty/>使用百度前必讀</ a>  < a href= >意見反饋</ a> 京ICP證030173號  < img src=//www.baidu.com/img/gs.gif> </p > </div> </div> </div> </body> </html>\r\n'

requests庫的詳細介紹:

(以後再補上)

Requests庫應用的固定格式:

import requests

def getHTMLText(url):
    try:
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""

BeautifulSoup 庫

BeautifulSoup 庫介紹:

(以後補上)

劃重點:BeautifulSoup庫的基本使用中,注意NavigableString元素型別及<Tag>.string的使用;程式碼如下:

text =  "<li><a class=B href=//www.dianping.com/beijing/ch10/g112>大眾點評</a></li>"
soup = BeautifulSoup(text,"html.parser")
str = soup.li.string
str1 = soup.li.a.string
str2 = soup.a.string
#這裡str=str1=str2
type(str) = bs4.element.NavigableString


text1 = "<li>大眾點評<a class=B href=//www.dianping.com/beijing/ch10/g112></a></li>"
soup = BeautifulSoup(text1,"html.parser")
str = soup.li.string
error

text2 = "<li><a class=B href=//www.dianping.com/beijing/ch10/g112></a>大眾點評</li>"
soup = BeautifulSoup(text2,"html.parser")
str = soup.li.string
error

#當一個tag中既有tat.children,又有NavigableString時,不識別<Tag>.string,且type()預設為none。
此時應該用<Tag>.text來取出Tag中的string。

完整程式碼示例:

 

#-*- coding:utf-8 -*-
#Crawlandmark_trading area.py
#商區,地標爬取

import numpy as np
import pandas as pd
from pandas import Series,DataFrame

import requests

from bs4 import BeautifulSoup
import bs4

def getHTMLText(url):
    try:
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""
        
def fillSQList(sqlist, html):
    soup = BeautifulSoup(html,"html.parser")
    for div in soup.find_all("div", "box shopallCate"):
        if div.find("h2").text == "商區":
#        if div.find("h2").text == "地標":
            for dl in div.find_all("dl"):
                NaN = ""
                sqlist.append([dl.find("dt").text,NaN])
                for li in dl.find_all("li"):
                    sqlist.append([NaN,li.a.string])
                        

def toCsv(sqlist):
    sqlist = pd.DataFrame(data = sqlist)
    sqlist.to_csv('商區.csv',encoding='utf_8_sig')
#    sqlist.to_csv('地標.csv',encoding='utf_8_sig')
if __name__ == '__main__':
    sqlist = []
    url = "http://www.dianping.com/shopall/2/0#BDBlock"
    html = getHTMLText(url)
    fillSQList(sqlist, html)
    toCsv(sqlist)