【问题标题】:Scrape URL provided by CSVCSV 提供的抓取 URL
【发布时间】:2017-12-05 17:10:46
【问题描述】:

我有一个包含一些数据列的 CSV,第 15 列报告了一个 URL 列表。现在,我需要从列中选择每个 URL,从目标网页中抓取新价格,然后将其存储在价格列中以更新旧价格。

没有相同的列枚举,这里是一个近似的CSV:

asin,title,product URL,price
KSKFUSH01,Product Title,http://....,56.00

以下是我编写的示例代码,但它只是打印 URL :(

import csv

with open('some.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)

for line in csv_reader:
    print(line[15])

对实现这一目标有任何帮助或建议吗?

谢谢

【问题讨论】:

  • 您有示例网址吗?我建议研究一下 BeautifulSoup
  • 你好教程看起来很棒,这是示例 URL:amazon.it/dp/B006H9B6XI,但基本上我不知道如何从 csv 文件中读取每个 URL
  • 如果 csv 有正确命名的列,您可以用逗号分隔每一行以提取 URL。
  • 我得到一个错误:AttributeError: 'list' object has no attribute 'split'
  • 你的文字很难解析。您的示例 csv 与您的描述不符。我正在更新我的答案。

标签: python csv


【解决方案1】:

您似乎想使用 csv 编写器。您可以访问每一行中的 URL。以下是您可以编写新价格的方法。

import csv
import urllib2
from bs4 import BeautifulSoup
with open('some.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)

with open('newPricedata.csv', 'w', newline='') as Newcsvfile:
Pricewriter = csv.writer(Newcsvfile, delimiter=' ',
                        quotechar='|', quoting=csv.QUOTE_MINIMAL)
for line in csv_reader:
page = urllib2.urlopen(line[15])
soup = BeautifulSoup(page, ‘html.parser’)
price = soup.find(‘td’, attrs={‘class’: ‘a-size-mini a-color-price ebooks-price-savings a-text-normal'})
Pricewriter.writerow(line[0]+','+,line[1]+','....+price.text)

【讨论】:

  • 似乎我无法拆分字符串
  • 我用一些可以帮助你的基本代码更新了我的答案。
  • 这样做是不好的。阅读这篇文章:stackoverflow.com/questions/3146571/…
  • 好的,谢谢!我现在要测试你的代码,看起来很专业!
【解决方案2】:

这是一个关于如何使用 BeautifulSoup 抓取网站的好指南 https://medium.freecodecamp.org/how-to-scrape-websites-with-python-and-beautifulsoup-5946935d93fe

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-29
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    相关资源
    最近更新 更多