python - 从字符串中选择单词时,使用 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()
解决方案
欢迎来到 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!
推荐阅读
- python - 设置初始 Django ModelForm 字段值的问题
- python-3.x - 使用 ec2-ubuntu 服务器在 aws 中托管网站
- hibernate - 具有来自不同表的外部引用的休眠复合键
- r - 如何在ggplot线图中将y轴从负值固定为正值
- node.js - sequelize 和 postgres 中关联表中的多个值
- angular - foreach 不是 Angular 8 中的函数
- wordpress - 如何在不使用开关盒的情况下在 woocommerce 中添加货币符号后缀
- python - 为什么 record = cur.fetchone()[0] 突然变成了 Nonetype
- javascript - 如何使用参数设置 Express 路由
- amazon-web-services - 我可以使用 lambda 将数据从 s3 导出到 dynamoDB 吗?