python

怎么用python爬取文本内容并保存

小亿
99
2023-11-07 13:38:34
栏目: 编程语言

要用Python爬取文本内容并保存,可以按照以下步骤进行:

  1. 导入所需的库:首先,导入requests库,用于发送HTTP请求获取网页内容;导入BeautifulSoup库,用于解析网页内容。
import requests
from bs4 import BeautifulSoup
  1. 发送HTTP请求并获取网页内容:使用requests库的get方法发送GET请求,并通过text属性获取网页内容。
url = '要爬取的网页URL'
response = requests.get(url)
html = response.text
  1. 解析网页内容:使用BeautifulSoup库解析网页内容,并提取所需的文本信息。
soup = BeautifulSoup(html, 'html.parser')
text = soup.get_text()
  1. 保存文本内容:将提取到的文本内容保存到文件中,可使用open函数打开一个文件,然后使用write方法写入内容。
with open('保存的文件路径', 'w', encoding='utf-8') as file:
    file.write(text)

完整代码示例:

import requests
from bs4 import BeautifulSoup

url = '要爬取的网页URL'
response = requests.get(url)
html = response.text

soup = BeautifulSoup(html, 'html.parser')
text = soup.get_text()

with open('保存的文件路径', 'w', encoding='utf-8') as file:
    file.write(text)

请将代码中的要爬取的网页URL替换为你需要爬取的网页的URL,保存的文件路径替换为你希望保存的文件路径。

0
看了该问题的人还看了