本文共 2493 字,大约阅读时间需要 8 分钟。
Beautiful Soup 是一个功能强大的 Python 库,专门用于从 HTML 或 XML 文件中提取数据。常见的应用场景包括网页爬虫、数据解析等。以下将介绍如何利用 Beautiful Soup 从网页中提取所需数据。
requests
库获取目标网页的 HTML 内容。首先,导入必要的库和模块:
import requestsfrom bs4 import BeautifulSoup
接下来,使用 requests.get()
获取网页内容。请注意,部分网页可能需要设置合适的 User-Agent
和正确的 encoding
:
url = "https://labfile.oss.aliyuncs.com/courses/2184/2019%E8%BD%AF%E7%A7%91%E4%B8%96%E7%95%8C%E5%A4%A7%E5%AD%A6%E5%AD%A6%E6%9C%AF%E6%8E%92%E5%90%8D.html"response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4452.106 Safari/537.36'})response.encoding = response.apparent_encoding # 确定编码格式html = response.text # 获取网页内容
使用 BeautifulSoup
对 HTML 内容进行解析。常用的解析器包括 html.parser
、lxml
和 html5lib
。以下使用 html.parser
:
soup = BeautifulSoup(html, 'html.parser')
Beautiful Soup 提供了丰富的方法来查找和遍历文档树。例如,find()
方法用于查找第一个匹配的标签,find_all()
方法用于查找所有匹配的标签。
tbody
标签由于需要提取表格中的数据,首先需要找到 tbody
标签:
tbody = soup.find('tbody')for child in tbody.find_all('tr'): print(child)
在 tbody
标签下,通常存在多个 tr
标签,每个 tr
标签下又包含多个 td
标签。我们可以使用 find_all()
方法来获取所有 td
标签,并提取其中的文本内容:
info = []for tr in tbody.find_all('tr'): tds = tr.find_all('td') for td in tds: info.append(td.string)print(info)
除了 find()
和 find_all()
,还可以使用 search()
方法来进行更灵活的搜索。例如,可以指定标签名和属性来筛选特定内容。
search()
方法results = soup.search('td', {'class': 'rank'})for item in results: print(item)
以下是一个用于爬取课程信息的示例代码:
import requestsfrom bs4 import BeautifulSoupurl = "https://www.lanqiao.cn/courses/"response = requests.get(url)response.encoding = response.apparent_encodingdemo = response.textsoup = BeautifulSoup(demo, 'html.parser')divs = soup.find_all('div', 'course-cover relative')info_dict = {}for div in divs: href = div.find('a', 'link block').get('href') title = div.find('h3').get('title') info_dict[title] = hrefprint(info_dict)
以下是一个用于爬取图片信息的示例代码:
import requestsfrom bs4 import BeautifulSoupurl = "https://www.example.com/images"response = requests.get(url)response.encoding = response.apparent_encodinghtml = response.textsoup = BeautifulSoup(html, 'html.parser')imgs = soup.find_all('img')for img in imgs: print(img.get('src')) # 获取图片路径 print(img.get('alt')) # 获取图片描述
通过以上步骤,可以轻松地使用 Beautiful Soup 从网页中提取所需数据。无论是表格数据还是图片信息,都可以通过灵活的查找和遍历方法实现。记住,熟练掌握这些技巧是网页爬虫开发中的关键所在。
转载地址:http://nqrwz.baihongyu.com/