为什么我的CSV文件在代码运行时没有错误而显示为空



我对编码非常陌生,并试图获得一个基本的webcrapping代码。代码运行得很好,问题是我无法获得CSV文件中的任何信息。如果有任何帮助,我们将不胜感激。

from bs4 import BeautifulSoup
import requests
import csv
page_to_scrape = requests.get("https://www.scrapethissite.com/pages/")
soup = BeautifulSoup(page_to_scrape.text, "html.parser")
descriptions = soup.findAll("p", attrs=("class" == "lead session-desc"))
titles = soup.findAll("h3", attrs=("class" == "page-title"))
with open("scrapeinformation.csv", "w", newline="") as f:
thewriter = csv.writer(f)
for title, desc in zip(titles, descriptions):
print(title.text + " - " + desc.text)
thewriter.writerow([title.text, desc.text])
f.close()

您是否绝对确定csv为空?当我运行您的代码时,我注意到当我在Excel上查看时,文件看起来是空的,但如果我用记事本或Google Sheets打开,就不会了,而且print(title.text + " - " + desc.text)显示单元格条目被很多空白包围。

因此,实际上Excel单元格只是在开头显示空白,因为默认格式显示的内容并不超过单元格中的内容。我可以在I:之后看到内容

  1. Ctrl+A选择全部,然后
  2. Alt+H+W切换"环绕文本"设置(如果第一次似乎没有差异,请尝试再次切换(

但是,我个人在这里建议的方法是首先删除空白-您可以使用strip()方法(如.text.strip()(或使用.get_text(strip=True)而不是.text

相关内容

最新更新