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

46次阅读
没有评论

共计 863 个字符,预计需要花费 3 分钟才能阅读完成。

要用 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,保存的文件路径 替换为你希望保存的文件路径。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-16发表,共计863字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)