首页 > 解决方案 > 从字符串中选择单词时,使用 BeautifulSoup Python 从字符串中删除不需要的字符

问题描述

我是 Python 新手,仍然不了解它的所有内容及其功能,但我正在接近我想要实现的目标。

本质上,我有程序可以从网站上抓取我想要的数据,但是当它从“specs”字符串中打印选定的单词/项目时,它也会从字符串中打印 [ ] 和 '' 等字符。

例如,我试图从 li 列表中获取“齿轮箱”类型、“燃料”类型和“里程”,我已将其转换为带有工厂的字符串,然后从该字符串中选择特定项目。

我从当前程序中得到的是:

['手动']['汽油']['86,863英里']

我想要实现的是这样的打印结果:

手动,汽油,86,863 英里

当导出到我的 .csv 中的单独列时,它应该显示在相应标题下的正确列中。

我曾尝试 .text 仅删除文本,但它显示为“列表”对象没有属性“文本”错误。


import csv 

import requests
from bs4 import BeautifulSoup

outfile = open('pistonheads.csv','w', newline='')
writer = csv.writer(outfile)
writer.writerow(["Link", "Make", "Model", "Price", "Image Link", 
"Gearbox", "Fuel", "Mileage"])

url = 'https://www.pistonheads.com/classifieds?Category=used- cars&Page=1&ResultsPerPage=100'

get_url = requests.get(url)
get_text = get_url.text

soup = BeautifulSoup(get_text, 'html.parser')
car_link = soup.find_all('div', 'listing-headline', 'price')

for div in car_link:
    links = div.findAll('a')
    for a in links:
        link = ("https://www.pistonheads.com" + a['href'])
        make = (a['href'].split('/')[-4])
        model = (a['href'].split('/')[-3])
        price = a.find('span').text.rstrip()
        image_link = a.parent.parent.find('img')['src']
        image = ("https:") + image_link
        vehicle_details = a.parent.parent.find('ul', class_='specs')
        specs = list(vehicle_details.stripped_strings)
        gearbox = specs[3:]
        fuel = specs[1:2]
        mileage = specs[0:1]
        writer.writerow([link, make, model, price, image, gearbox, fuel, mileage])
        print(link, make, model, price, image, gearbox, fuel, mileage)

outfile.close()

标签: pythonbeautifulsoupscreen-scraping

解决方案


欢迎来到 StackOverflow!

因此,您的脚本有很多需要改进的地方。你快到了!

  • specs = list(vehicle_details.stripped_strings)是解析为列表的生成器。实际上,您可以通过索引访问您想要的东西。例如,mileage可以简单地是specs[0].
  • 您获得额外的问题[]由您使用 slicing 引起的mileage = specs[0:1]。从文档中,索引返回一个项目,切片返回一个新列表。见列表介绍
  • (可选)最后,要在一行中获取所有这些信息,您可以从规格列表中​​进行多项分配。查看多个作业。
mileage, fuel, _, gearbox = specs
  • 额外提示如有疑问,请使用pdb
mileage = specs[0]
import pdb; pdb.set_trace()  # temp set on one line so you can remove it easily after
# now you can interactively inspect your code
(Pdb) specs

祝你好运!并享受 Python!


推荐阅读