代码-功能-Python-运用bs4技术爬取汽车之家新闻信息

第三方库安装指令:

python 复制代码
pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install BeautifulSoup4 -i https://pypi.tuna.tsinghua.edu.cn/simple

运行代码:

python 复制代码
#这个代码并不完整,有很大的问题,但目前不知道怎么改,就先这样吧!
import requests
from bs4 import BeautifulSoup
header={
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
}

begin = int(input("请输入开始页码:"))
end = int(input("请输入结束页码:"))

def save(titles):
    with open("1.html", 'w', encoding='utf-8') as file:
        x=str(titles)
        file.write(x)
title_ls=[]
content_ls=[]
for page in range(begin,end+1):
    url = f"https://www.autohome.com.cn/news/{page}/#liststart"
    rsp = requests.get(url,headers=header)
    bs4=BeautifulSoup(rsp.text,features='lxml')
    titles=bs4.find_all("h3")[1:]
    for title in titles:
        title_ls.append(title.text)

    contents = bs4.find_all("p")[3:]
    for content in  contents:
        content_ls.append(content)
titles=dict(zip(title_ls,content_ls))
save(titles)
print("爬取完毕")
相关推荐
pluvium279 分钟前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh
cmpxr_10 分钟前
【C】原码和补码以及环形坐标取模算法
c语言·开发语言·算法
2401_8274999923 分钟前
python项目实战09-AI智能伴侣(ai_partner_5-6)
开发语言·python
PD我是你的真爱粉25 分钟前
MCP 协议详解:从架构、工作流到 Python 技术栈落地
开发语言·python·架构
ZhengEnCi29 分钟前
P2G-Python字符串方法完全指南-split、join、strip、replace的Python编程利器
python
是小蟹呀^43 分钟前
【总结】LangChain中工具的使用
python·langchain·agent·tool
宝贝儿好1 小时前
【LLM】第二章:文本表示:词袋模型、小案例:基于文本的推荐系统(酒店推荐)
人工智能·python·深度学习·神经网络·自然语言处理·机器人·语音识别
星晨雪海1 小时前
基于 @Resource 的支付 Service 多实现类完整示例
java·开发语言
王夏奇1 小时前
pythonUI界面弹窗设置的几种办法
python·ui
ACP广源盛139246256731 小时前
破局 Type‑C 切换器痛点@ACP#GSV6155+LH3828/GSV2221+LH3828 黄金方案
c语言·开发语言·网络·人工智能·嵌入式硬件·计算机外设·电脑