【问题标题】:Python Script Running through Command Line Not Creating CSV通过命令行运行的 Python 脚本不创建 CSV
【发布时间】: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


【解决方案1】:

我发现您编写 csv 的代码运行良好。这里是孤立的

import csv

vehicle = {'data-make': 'Buick',
           'data-type': 'Sedan',
           'data-location': 'Bronx',
           }
price = '8000.00'
vin = '11040VDOD330C0D0D003'
link = 'https://www.necarconnection.com/someplace'
img_url = 'https://www.necarconnection.com/image/someimage'
comment = 'Fine Car'

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})

它创建了 necc-december.csv 罚款:

CLASSIFICATION,TYPE,PRICE,VIN,INDEX,LINK,IMG,DESCRIPTION
Buick,Sedan,8000.00,11040VDOD330C0D0D003,Bronx,https://www.necarconnection.com/someplace,https://www.necarconnection.com/image/someimage,Fine Car

我认为问题在于代码没有找到任何带有 class='next' 的按钮

要运行您的代码,我必须初始化 next_url

next_url = None

然后改变你的条件

if next_url not in urls:

If next_url and next_url not in urls:

我在你的 for 循环中添加了调试:

for button in soup.find_all('a',class_='pages'):
    print ('button:', button)

得到了这个输出:

button: <a class="pages current" data-page="1" href="javascript:void(0);">1</a>
button: <a class="pages" data-page="2" href="javascript:void(0);">2</a>
button: <a class="pages" data-page="3" href="javascript:void(0);">3</a>
button: <a class="pages" data-page="4" href="javascript:void(0);">4</a>
button: <a class="pages" data-page="5" href="javascript:void(0);">5</a>
button: <a class="pages" data-page="6" href="javascript:void(0);">6</a>
button: <a class="pages current" data-page="1" href="javascript:void(0);">1</a>
button: <a class="pages" data-page="2" href="javascript:void(0);">2</a>
button: <a class="pages" data-page="3" href="javascript:void(0);">3</a>
button: <a class="pages" data-page="4" href="javascript:void(0);">4</a>
button: <a class="pages" data-page="5" href="javascript:void(0);">5</a>
button: <a class="pages" data-page="6" href="javascript:void(0);">6</a>

所以没有 class= 'next' 的按钮。

【讨论】:

    猜你喜欢
    • 2017-09-13
    • 1970-01-01
    • 2021-03-20
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多