使用BeautifulSoup爬取的数据在Excel中显示为代码形式如何解决?
解决OLX爬虫导出Excel非结构化问题
你的脚本导出Excel出现非结构化的“代码形式”内容,核心原因是列表中混合了BeautifulSoup元素对象和文本字符串,Pandas导出时会把对象转为其字符串表示(也就是你看到的类似<div class="a5112ca8">...</div>的内容),同时循环内的字段提取逻辑完全错误。
修复后的完整代码
from bs4 import BeautifulSoup import requests import pandas as pd import time # 请求页面 result = requests.get('https://www.olx.com.eg/en/ads/q-%D8%B5%D9%8A%D8%AF%D9%84%D9%8A%D8%A9/') time.sleep(4) soup = BeautifulSoup(result.text, 'html.parser') # 初始化空列表用于存储文本数据 titles = [] prices = [] areas = [] locations = [] posted_dates = [] # 提取页面元素集合(不直接覆盖数据列表) title_elements = soup.find_all('div', {'class': 'a5112ca8'}) price_elements = soup.find_all('div', {'class': '_52497c97'}) area_elements = soup.find_all('div', {'class': 'a8f6df88'}) location_elements = soup.find_all('span', {'class': '_424bf2a8'}) posted_elements = soup.find_all('span', {'class':'_2e28a695'}) # 循环提取对应字段的文本内容 # 以最短的元素列表长度为准,避免索引越界 max_len = min(len(title_elements), len(price_elements), len(area_elements), len(location_elements), len(posted_elements)) for i in range(max_len): titles.append(title_elements[i].text.strip()) prices.append(price_elements[i].text.strip()) areas.append(area_elements[i].text.strip()) locations.append(location_elements[i].text.strip()) posted_dates.append(posted_elements[i].text.strip()) # 创建DataFrame并导出Excel df = pd.DataFrame({ 'Title': titles, 'Price': prices, 'Area': areas, 'Location': locations, 'Posted': posted_dates }) df.to_excel(r"D:\Python\Unfinished projects\Olx\Olx Scrapping.xlsx", index=False)
关键修复点
- 分离元素集合与数据列表:不再用
titles = soup.find_all(...)覆盖空列表,而是用单独变量存储页面元素,避免列表中混合对象和文本 - 正确提取对应字段:循环中分别从各自的元素集合提取文本,不再所有字段都复用标题的文本内容
- 避免索引越界:取所有元素集合的最小长度作为循环上限,防止部分字段缺失导致报错
- 统一创建DataFrame:把DataFrame的创建放到循环外部,提升效率且逻辑更清晰
内容的提问来源于stack exchange,提问作者Ahmed Ibrahim
相关产品推荐
相关产品推荐

