代码-功能-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("爬取完毕")
相关推荐
KimLiu11 分钟前
LCODER之Python:使用Django搭建服务端
后端·python·django
胡耀超14 分钟前
3.Python高级数据结构与文本处理
服务器·数据结构·人工智能·windows·python·大模型
云:鸢15 分钟前
C语言链表设计及应用
c语言·开发语言·数据结构·链表
准测仪器21 分钟前
新能源汽车中维修开关有什么作用?
汽车·电动汽车·仪器仪表·msd·维修开关·准测仪器
1373i31 分钟前
【Python】pytorch安装(使用conda)
pytorch·python·conda
keyinf034 分钟前
python网络爬取个人学习指南-(五)
python
kida_yuan1 小时前
【从零开始】12. 一切回归原点
python·架构·nlp
离越词1 小时前
C++day8作业
开发语言·c++·windows
℃CCCC1 小时前
请求库-axios
开发语言·华为·网络请求·harmonyos·deveco studio·axios请求·arkts编程