代码-功能-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("爬取完毕")
相关推荐
dlraba8024 分钟前
用 Python+OpenCV 实现实时文档扫描:从摄像头捕捉到透视矫正全流程
开发语言·python·opencv
小熊出擊10 分钟前
【pytest】fixture 内省(Introspection)测试上下文
python·单元测试·pytest
njsgcs30 分钟前
sse mcp flask 开放mcp服务到内网
后端·python·flask·sse·mcp
一人の梅雨39 分钟前
1688 店铺商品全量采集与智能分析:从接口调用到供应链数据挖掘
开发语言·python·php
小何好运暴富开心幸福1 小时前
C++之日期类的实现
开发语言·c++·git·bash
威风的虫1 小时前
JavaScript中的axios
开发语言·javascript·ecmascript
老赵的博客1 小时前
c++ 是静态编译语言
开发语言·c++
Terio_my1 小时前
Python制作12306查票工具:从零构建铁路购票信息查询系统
开发语言·python·microsoft
消失的旧时光-19432 小时前
Kotlin when 用法完整分享
android·开发语言·kotlin
万粉变现经纪人2 小时前
如何解决 pip install -r requirements.txt 约束文件 constraints.txt 仅允许固定版本(未锁定报错)问题
开发语言·python·r语言·django·beautifulsoup·pandas·pip