要用Python爬取文本内容并保存,可以按照以下步骤进行:
导入所需的库:首先,导入requests库,用于发送HTTP请求获取网页内容;导入BeautifulSoup库,用于解析网页内容。import requestsfrom bs4 import BeautifulSoup发送HTTP请求并获取网页内容:使用requests库的get方法发送GET请求,并通过text属性获取网页内容。url = '要爬取的网页URL'response = requests.get(url)html = response.text解析网页内容:使用BeautifulSoup库解析网页内容,并提取所需的文本信息。soup = BeautifulSoup(html, 'html.parser')text = soup.get_text()保存文本内容:将提取到的文本内容保存到文件中,可使用open函数打开一个文件,然后使用write方法写入内容。with open('保存的文件路径', 'w', encoding='utf-8') as file: file.write(text)完整代码示例:
import requestsfrom bs4 import BeautifulSoupurl = '要爬取的网页URL'response = requests.get(url)html = response.textsoup = BeautifulSoup(html, 'html.parser')text = soup.get_text()with open('保存的文件路径', 'w', encoding='utf-8') as file: file.write(text)请将代码中的要爬取的网页URL替换为你需要爬取的网页的URL,保存的文件路径替换为你希望保存的文件路径。

