代码-功能-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("爬取完毕")
相关推荐
曹牧1 分钟前
C#:ToDouble
开发语言·c#
袁袁袁袁满4 分钟前
Python读取doc文件打印内容
开发语言·python·python读取doc文件
zcfeng53016 分钟前
PHP升级
开发语言·php
m0_7482523819 分钟前
Ruby 模块(Module)的基本概念
开发语言·python·ruby
羊小猪~~22 分钟前
【QT】-- QT基础类
开发语言·c++·后端·stm32·单片机·qt
子午27 分钟前
【2026原创】水稻植物病害识别系统~Python+深度学习+人工智能+resnet50算法+TensorFlow+图像识别
人工智能·python·深度学习
深蓝电商API29 分钟前
Scrapy ImagesPipeline和FilesPipeline自定义使用
爬虫·python·scrapy
木卫二号Coding32 分钟前
Python-文件拷贝+文件重命名+shutil+记录
开发语言·python
bubiyoushang8881 小时前
基于Q-learning的路径规划MATLAB仿真程序实现
开发语言·matlab
爬山算法1 小时前
Hibernate(44)Hibernate中的fetch join是什么?
前端·python·hibernate