示例代码说明:
在汽车之家网站拉取当月排行榜中汽车品牌、销量和价格信息,存为csv文档输出,使用正则表达式获取网页内容
import re
import pandas as pd
import requests# 汽车之家车型列表页URL
url = 'https://cars.app.autohome.com.cn/carext/recrank/all/getrecranklistpageresult2?from=28&pm=2&pluginversion=11.65.0&model=1&channel=0&pageindex=1&pagesize=650&typeid=1&subranktypeid=1&levelid=0&price=0-9000&date=2025-02'
# 读取内容
urltext = requests.get(url).text
#汽车品牌
seriesnamedata = re.findall('"seriesname":"(.*?)"', urltext)
#汽车销量
righttextonedata = re.findall('"righttextone":"(.*?)"', urltext)
#去除销量列表中的空字符串
righttextonedataupdate=list(filter(None, righttextonedata))
#汽车价格
priceinfodata = re.findall('"priceinfo":"(.*?)"', urltext)
print('************************************---------------------------------***********************************')
# 转换为DataFrame并保存
if seriesnamedata: df1 = pd.DataFrame({"品牌": seriesnamedata})df2 = pd.DataFrame({"销量": righttextonedataupdate})df3 = pd.DataFrame({"价格": priceinfodata})combined_df = pd.concat([df1, df2, df3], axis=1)combined_df.to_csv("autohome_brands.csv", index=False, encoding="utf_8_sig")print(f"成功提取 {len(combined_df)} 个品牌")
else:print("未找到品牌数据")
结果示例: