【问题标题】:Removing spaces from lines in python从python中的行中删除空格
【发布时间】:2020-05-11 08:56:59
【问题描述】:

我一直在制作这个脚本来从购物网站中提取价格以获得最优惠价格的机会,但是我知道为什么我不能从行中删除空格,尝试了 strip 和 re 但似乎没有一个工作。 感谢您的回答
我是一名对编程感兴趣的医务人员,这就是为什么我不是很熟练 这是代码:

import requests
from bs4 import BeautifulSoup
import re
file = open('weird.txt' , "w+" , encoding='utf8')
out = open("output.txt" , "w+" , encoding = 'UTF-8')
url = "https://www.lioncomputer.com/computer/computer-components/motherboard.html?lion_599=26179%2C26175&product_list_dir=asc"
page = requests.get(url)
page = page.text
soup = BeautifulSoup(page , 'html5lib')
file.write(soup.prettify())
soup2 = soup.find('ol' , class_ = 'products list items product-items')
item = soup2.find_all('div' ,class_ ="product details product-item-details")
for i in item :
    name =i.find(class_= "product-item-link")
    name = name.get_text()
    price = i.find(class_="price-box price-final_price")
    price = price.get_text()
# text = i.find('a' , class_ = 'product-item-link')
    out.write(("{0}:{1}".format(name,price)))
with open('outpuT.txt' , "w+") as f :
    for line in f:
        cleaned = line.replace((re.find((' ')[6])), '')
        cleaned = cleaned.strip()
        f.write(cleaned)

【问题讨论】:

  • 请举个例子
  • 贴出你试过的代码
  • 一个类似的问题已经在这里回答了stackoverflow.com/questions/8270092/…希望它有所帮助!
  • 你试过strip法吗?
  • 是的,正如我在标题中提到的,我尝试了剥离和重新但没有用

标签: python


【解决方案1】:

您可以使用python中的替换功能来删除空格。

newUpdatedString = oldString.replace("  ","")

但是,请记住,此命令将删除所有连续的空格。

【讨论】:

  • 试过但不工作你能运行代码吗? /跨度>
  • 您尝试访问的站点返回 403 禁止代码。我对此无能为力:(
  • 啊 sryy 伊朗安全逻辑:不要让他们从外国 IP 连接,以防被黑客入侵,我们很容易找到大声笑,如果你愿意,我可以发送页面源
猜你喜欢
  • 2022-01-20
  • 2012-10-20
  • 2013-09-25
  • 1970-01-01
  • 2013-10-10
  • 2017-11-03
  • 2015-04-21
  • 1970-01-01
  • 2016-08-25
相关资源
最近更新 更多