代码-功能-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("爬取完毕")
相关推荐
紫丁香2 分钟前
pytest_自动化测试5
python·功能测试·单元测试·集成测试·pytest
永远睡不够的入2 分钟前
C++庖丁解牛:深入理解多态:从虚函数表到底层实现
开发语言·c++
姚青&4 分钟前
Pytest fixture 参数化(params 参数)
开发语言·python·pytest
2301_793804695 分钟前
深入理解Python的if __name__ == ‘__main__‘
jvm·数据库·python
qyzm6 分钟前
牛客周赛 Round 136
数据结构·python·算法
qq_334903156 分钟前
C++与人工智能框架
开发语言·c++·算法
紫檀香7 分钟前
Alembic入门教程
后端·python
2401_891482178 分钟前
C++中的状态模式
开发语言·c++·算法
2401_833197738 分钟前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
wayz1110 分钟前
DuckDB 完全指南:从入门到精通
python·金融·量化交易