脚本及命令系列 5"/>
【Python 常用脚本及命令系列 5
文章目录
- Python BeautifulSoup 介绍
- CSDN 网页表格解析
- 开发问题总结
Python BeautifulSoup 介绍
BeautifulSoup是一个Python库,用于解析HTML和XML文档。它常常用于网络爬虫来提取网页中的信息。
以下是BeautifulSoup的一些主要特性:
-
解析HTML:BeautifulSoup能够解析HTML字符串,并将其转化为一个复杂的树形结构,每个HTML标签都成为树中的一个节点。
-
搜索节点:你可以使用多种方式搜索树中的节点,例如根据标签名、根据CSS类名、根据属性等。
-
修改文档:你还可以使用BeautifulSoup来修改HTML文档,例如改变标签的名称、改变标签的属性、添加新的标签等。
以下是一个简单的BeautifulSoup使用示例:
from bs4 import BeautifulSoup
# 创建BeautifulSoup对象
soup = BeautifulSoup("<html><body><h1>Hello, World!</h1></body></html>", "html.parser")
# 找到h1标签
h1_tag = soup.find("h1")
# 打印h1标签的文本
print(h1_tag.text)
# 输出: Hello, World!
在这个示例中,我们首先创建了一个BeautifulSoup对象,并给它提供了一段HTML字符串以及解析器的名字。然后,我们使用find方法找到了h1标签,并打印出了它的文本。
要注意的是,BeautifulSoup本身并不下载网页,所以通常我们会配合使用requests等库来首先下载网页。
CSDN 网页表格解析
使用Python进行网络爬虫时,我们通常使用 BeautifulSoup 或者 lxml 这样的库来解析网页。这里提供一个使用 requests 和BeautifulSoup 来爬取 CSDN 网页上表格内容的基本示例:
import sys, os, time
import requests
from bs4 import BeautifulSoup
import pandas as pdf = open("csdn.txt", 'w')# 请求网页
#url = "你的网页URL"
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' }
#response = requests.get(url)
response = requests.get(url, headers=headers)soup = BeautifulSoup(response.text, 'html.parser')tables = soup.find_all("table")
for i, table in enumerate(tables):
# for table in tables:
#table = soup.find('table')f.write("|--------------------------\n")thead = table.find("thead")rows = thead.find_all('tr')for row in rows:columns = row.find_all('th')for column in columns:print(column.get_text())# "| | | |" table format used for CSDNdata = "|" + column.get_text()f.write(data)crlf = "|" + "\n"f.write(crlf)# "|-|-|-|" table format used for CSDNfor column in columns:csdn_str = "|-"f.write(csdn_str)f.write("|\n")tbody = table.find('tbody')rows = tbody.find_all('tr')for row in rows:columns = row.find_all('td')for column in columns:print(column.get_text())data = "|" + column.get_text()f.write(data)# "| | | |" table format used for CSDNcrlf = "|" + "\n"f.write(crlf)f.close()
开发问题总结
在开发脚本时使用 python lxml 库遇到下面问题:
bs4.FeatureNotFound: Couldn’t find a tree builder with the features you requested . Do you need to install a parser library?
解决方法,
将
soup = BeautifulSoup(response.text, 'lxml')
修改为:
soup = BeautifulSoup(response.text, 'html.parser')
更多推荐
【Python 常用脚本及命令系列 5
发布评论