简体   繁体   English

python csv导入链接

[英]python csv importing to link

I am trying to get Python to open sites based on a csv file. 我正在尝试让Python打开基于csv文件的站点。 I checked all of my code individually to make sure it worked and it does but when I introduce this variable from the csv file I am getting the error message below: Here is the code: 我单独检查了所有代码以确保它可以正常工作,但是当我从csv文件中引入此变量时,出现以下错误消息:这是代码:

import urllib
import urllib.request
from bs4 import BeautifulSoup
import os

import csv

f = open('gropn1.csv')
csv_f = csv.reader(f)

for row in csv_f:

    theurl="http://www.grote.com/?s="+csv_f[1] + "&q1=1"
    thepage = urllib.request.urlopen(theurl)
    soup = BeautifulSoup(thepage,"html.parser")

    for partno in soup.find('h2',{"class":"single-product-number"}):
        print(partno)

    for link in soup.find('ul',{"class":"breadcrumbs"}).findAll('a'):
        print(link.text)



f.close()

Here is the error: 这是错误:

Traceback (most recent call last):
  File "grotestart2.py", line 13, in <module>
    theurl="http://www.grote.com/?s="+csv_f[1] + "&q1=1"
TypeError: '_csv.reader' object is not subscriptable

Any help would be greatly appreciated! 任何帮助将不胜感激! Thanks 谢谢

TypeError: '_csv.reader' object is not subscriptable TypeError:“ _ csv.reader”对象不可下标

csv_f is your csv reader instance and it is actually "not subscriptable" by definition. csv_f是您的csv阅读器实例 ,根据定义,它实际上是“不可下标的”

Did not you mean to use the row variable instead. 您不是要改用row变量。 Replace: 更换:

theurl="http://www.grote.com/?s="+csv_f[1] + "&q1=1"

with: 与:

theurl="http://www.grote.com/?s="+row[1] + "&q1=1"

You are also trying to iterate over the results of soup.find() call which is a Tag instance which is not iterable. 您还尝试对soup.find()调用的结果进行迭代,这是一个不可迭代Tag实例 You meant to use find_all() . 您打算使用find_all() Replace: 更换:

for partno in soup.find('h2',{"class":"single-product-number"}):

with: 与:

for partno in soup.find_all('h2', {"class":"single-product-number"}):

Or, a shorter version using a CSS selector : 或者,使用CSS选择器的较短版本:

for partno in soup.select('h2.single-product-number'):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM