【发布时间】:2018-12-13 16:51:37
【问题描述】:
我是 Python 新手,正在抓取网站以收集库存信息。库存项目分布在网站上的 6 个页面上。抓取进行得非常顺利,我能够解析出我想要选择的所有 HTML 元素。
我现在将其带到下一步,并尝试使用 Python 3 中包含的 csv.writer 将其导出到 csv 文件中。脚本在我的命令行中运行,没有弹出任何语法错误,但 csv 文件确实不被创造。我想知道我的脚本是否有任何明显的问题,或者我在尝试将解析的 HTML 元素放入 csv 时可能遗漏了一些问题。
这是我的代码:
import requests
import csv
from bs4 import BeautifulSoup
main_used_page = 'https://www.necarconnection.com/used-vehicles/'
page = requests.get(main_used_page)
soup = BeautifulSoup(page.text,'html.parser')
def get_items(main_used_page,urls):
main_site = 'https://www.necarconnection.com/'
counter = 0
for x in urls:
site = requests.get(main_used_page + urls[counter])
soup = BeautifulSoup(site.content,'html.parser')
counter +=1
for item in soup.find_all('li'):
vehicle = item.find('div',class_='inventory-post')
image = item.find('div',class_='vehicle-image')
price = item.find('div',class_='price-top')
vin = item.find_all('div',class_='vinstock')
try:
url = image.find('a')
link = url.get('href')
pic_link = url.img
img_url = pic_link['src']
if 'gif' in pic_link['src']:img_url = pic_link['data-src']
landing = requests.get(main_site + link)
souped = BeautifulSoup(landing_page.content,'html.parser')
comment = ''
for comments in souped.find_all('td',class_='results listview'):
com = comments.get_text()
comment += com
with open('necc-december.csv','w',newline='') as csv_file:
fieldnames = ['CLASSIFICATION','TYPE','PRICE','VIN',
'INDEX','LINK','IMG','DESCRIPTION']
writer = csv.DictWriter(csv_file,fieldnames=fieldnames)
writer.writeheader()
writer.writerow({
'CLASSIFICATION':vehicle['data-make'],
'TYPE':vehicle['data-type'],
'PRICE':price,
'VIN':vin,
'INDEX':vehicle['data-location'],
'LINK':link,
'IMG':img_url,
'DESCRIPTION':comment})
except TypeError: None
except AttributeError: None
except UnboundLocalError: None
urls = ['']
counter = 0
prev = 0
for x in range(100):
site = requests.get(main_used_page + urls[counter])
soup = BeautifulSoup(site.content,'html.parser')
for button in soup.find_all('a',class_='pages'):
if button['class'] == ['prev']:
prev +=1
if button['class'] == ['next']:
next_url = button.get('href')
if next_url not in urls:
urls.append(next_url)
counter +=1
if prev - 1 > counter:break
get_items(main_used_page,urls)
这是通过命令行处理脚本后发生的屏幕截图:
脚本运行需要一段时间,所以我知道脚本正在被读取和处理。我只是不确定这与实际制作 csv 文件之间出了什么问题。
我希望这会有所帮助。同样,任何关于使用 Python 3 csv.writer 的提示或技巧都将非常感谢,因为我尝试了多种不同的变体。
【问题讨论】:
-
您正在循环内写入 csv,因此每次通过都覆盖文件。而不是写尝试附加到文件。
with open('necc-december.csv','a',newline='') -
谢谢 - 您是否建议将该部分放在脚本的其他位置?我尝试取消缩进,但收到语法错误,显示“意外取消缩进”
-
自上次通过所有测试以来,您所做的最后一次更改是什么。会有错误。你在做测试驱动开发吗?如果没有,那么您需要调试它。调试是你在编程中会做的最难的事情,也许是你做过的最难的事情。为避免调试,请进行测试驱动开发。
-
@Sabrina。我会将所有信息存储在
dictionary中,在您将所有数据调用函数写入 CVS 并将所有数据写入文件之后
标签: python csv export-to-csv