代码-功能-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("爬取完毕")
相关推荐
chenshi1781几秒前
安全合规:使用 RPA 批量发布时,如何规避平台封禁风险,实现长效稳定的投喂?
python
老秦包你会12 分钟前
C++进阶------C++的类型转换
java·开发语言·c++
星辰烈龙12 分钟前
黑马程序员JavaSE基础加强d2
java·开发语言
superman超哥12 分钟前
仓颉性能瓶颈定位方法深度解析
c语言·开发语言·c++·python·仓颉
是苏浙17 分钟前
零基础入门Java之认识String类
java·开发语言
岁岁的O泡奶18 分钟前
NSSCTF_crypto_[SWPU 2020]happy
经验分享·python·算法·密码学
leaves falling21 分钟前
c语言-static和extern
c语言·开发语言
武汉唯众智创21 分钟前
“物联网 Python 开发教程”课程教学解决方案
开发语言·python·物联网·物联网技术·物联网 python 开发·python 开发
时光Autistic25 分钟前
【搭建教程】腾讯混元3D模型部署
开发语言·python·3d·github
前端程序猿之路26 分钟前
AI大模型应用之-RAG 全流程
人工智能·python·gpt·语言模型·aigc·mybatis·ai编程