python bs4模块 BeautifulSoup 学习笔记

时间:2025-05-13 08:43:51

bs4 模块的 BeautifulSoup 可以用来爬取html页面的内容,配合requests库可以写简单的爬虫。

1、利用requests请求html页面,获取HTML页面内容

import requests
from bs4 import BeautifulSoup


session = ()

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}

(headers)

# step 1  打开登陆页面
url = 'http://10.10.10.10/xx'
r = (url)
html = 

2、利用BeautifulSoup,解析HTML得到想要的信息

soup = BeautifulSoup(html, '')
# BeautifulSoup支持多种元素定位方式,也支持CSS定位,得到的是一个列表,列表中的元素信息可以用get方法获取
s1 = ('#id')[0].get('value')
#S1 就是对应元素value属性的值
print(s1)