python爬蟲之BeautifulSoup

一、安裝環境

1、pip install html5lib
2、pip install lxml
3、pip install beautifulsoup4

二、BeautifulSoup的簡單實用

一、解析本地html文件

soup = BeautifulSoup(open("alpha.html"))

二、匹配正則表達式

返回類型爲數組

test=soup.find_all(href=re.compile("build2079"))

如果需要獲取返回tag內的值,可以用string方法

alpha_url=soup.find_all(href=re.compile("build2079"),limit=1)[0].string

三、最簡單的demo

# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
from lxml import html
import xml
import requests,re
url = "https://www.baidu.com/"
f = requests.get(url)                 #Get該網頁從而獲取該html內容
#soup = BeautifulSoup(f.content, "lxml")  #用lxml解析器解析該網頁的內容, 好像f.text也是返回的html
test=soup.find_all(href=re.compile("build2079"))
print(test)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章