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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章