爬蟲(一) 解析本地網頁

2021-08-20 03:17:31 字數 1774 閱讀 2644

在網頁中的一段**

class='a'>

hello!p>

div>***

標籤,代表網頁中乙個區域框架,表示在區域中可裝什麼東西;標籤之間增加文字;class='a'為css修飾;標籤為列表,在列表題目前加個 點;標籤可以插入一張圖;h1-h6標籤代表不同字型大小的標題;標籤可載入鏈結。功能類似於縮排,在之前用。

一. 使用beautifulsoup解析網頁

#將html檔案用lxml引擎解析,放入soup中

soup = beautifulsoup(html檔案,'lxml')

#在解析出的檔案內容中挑選某個因素,select獲得的內容是列表

結果列表 = soup.select("css selector")

執行**時出現錯誤:unicodedecodeerror: 'gbk' codec can't decode byte 0xab in position 57: illegal multibyte sequence問題為讀取檔案時的字元編碼問題,在with open(path,』r』,encoding=』utf8』)可解決。with open("path",'r') as wb_data:其中『r』為讀取,『w』代表寫入。

二. 描述要爬取得東西在哪

變數 = soup.select(『元素路徑』)

如何找到路徑: 在網頁選定的物件處,右擊選檢查,在對應的html語句處,右擊選擇copy selector,將複製的內容貼上在元素路徑中即可。select()產生的是乙個列表,從標籤中獲得需要的資料時需要用到for迴圈。

css selector:body > div.attribute > ul...路徑表示 誰,在哪,第幾個,長什麼樣

xpath:/html/body/div[2]/ul/...路徑表示 誰,在哪,第幾個

三. 從標籤中獲得需要的資料

#zip函式用於將可迭代物件作為引數,將物件中對應的元素打包成乙個個元組,然後返回由這些元組組成的列表。

#titles = [1, 2, 3]

#images = [3, 4, 5]

#stars = [5, 6, 7]

#zip(titles, images, stars) = [(1,3,5),(2,4,6),(3,5,7)]

#大多數情況下,要提取的內容放在標籤中間 例`hello world

`,因此需要去除標籤,則使用get_text()函式得到標籤中間的內容

#鏈結放在標籤的src屬性裡,可利用get()得到屬性文字內容

for title, image, star in zip(titles, images, stars):

title_content = title.get_text()

image_content = image.get("src")

iOS WKWebView載入本地網頁

property strong,nonatomic wkwebview webview property nonatomic,copy nsstring url 我這裡是將html資源檔案放置在工程內乙個bundle的資料夾內 拼接後的網頁路徑 self url self componentfile...

ios webview載入本地網頁並解決亂碼問題

nsstring htmlstring nsstring stringwithcontentsoffile htmlpath webview loadhtmlstring htmlstring baseurl nil 如果需要用本地的話 baseurl 路徑設定為自己的resource 如果有亂碼問...

Tech Mac上安裝MAMP開啟本地網頁

不知道為什麼實驗室老是用些奇葩的東西,這次是madserve,主要是用來統計移動端廣告點選率的,基於php mysql實現。昨天很快在windows上搭好乙個xampp,並用它建立了乙個virtual host把madserve跑起來了。但是在mac上xampp建立virtual host一直報er...