爬取网易汽车文字-Python爬虫

网址链接:

https://auto.163.com/

准备工作:

首先需要安装 html2text re request 和bs4 这些库

代码实现:

import requests
import html2text
import re
from bs4 import BeautifulSoup

# 发起请求并获取网页内容
url = "https://auto.163.com/"
response = requests.get(url)
response.encoding = response.apparent_encoding

# 初始化 HTML2Text 转换器
h = html2text.HTML2Text()
h.ignore_links = True
h.ignore_images = True
h.ignore_emphasis = True

# 提取网页内容
text = response.text

# 切割不需要的内容
start_index = text.find("本地车市")
end_index = text.find("舟山")
if start_index != -1 and end_index != -1:
    trimmed_text = text[:start_index] + text[end_index + 2:]
else:
    trimmed_text = text

# 使用 BeautifulSoup 解析网页内容
soup = BeautifulSoup(trimmed_text, 'html.parser')

# 去除无关标签
for script in soup(["script", "style"]):
    script.extract()

# 获取文本内容
text = soup.get_text()

# 正则替换和处理文本
text = re.sub(r'\s+', ' ', text)
text = text.strip()
text = h.handle(text)

# 提取导航栏文本和内容文本
nav_start = text.find("网易汽车")
nav_end = text.find("热门车型")
nav_text = text[nav_start:nav_end]
content_text = text[nav_end:]

# 处理导航栏文本和内容文本
nav_text = re.sub(r'\s+', ' ', nav_text)
nav_text = nav_text.strip()
nav_text = h.handle(nav_text)
content_text = re.sub(r'\s+', ' ', content_text)
content_text = content_text.strip()
content_text = h.handle(content_text)

# 保存结果到文件
save_path = r'D:/python/Project/text/text.txt'
with open(save_path, 'w', encoding='utf-8') as file:
    file.write("导航栏文本:\n\n")
    file.write(nav_text)
    file.write("\n\n内容文本:\n\n")
    file.write(content_text)

print('文本保存成功!')
 

结果展示:展示了一部分

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值