2017-04-12 114 views
0

我有csv文件並且傳遞了csv數據有參數給python代碼。在csv文件中有URL數據。在python中調用URL的正確方法是什麼?收到錯誤Cannot navigate to invalid URL在python中調用URL的正確方法是什麼

CSV文件

ID,category,link 
sports_shoes,sports-shoes,https://www.flipkart.com/mens-footwear/sports-shoes/pr?otracker=categorytree&page=1&sid=osp%2Ccil%2C1cu 

代碼:

from selenium import webdriver 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 
from selenium.common.exceptions import TimeoutException 
from selenium.webdriver.common.by import By 
import time 
import csv 

with open('mydata.csv') as csvfile: 
    reader = csv.DictReader(csvfile) 
    for row in reader: 
     #print(row['ID'] ,row['category'],row['link']) 
     url = row['link'] 
     print(url) 
     chrome_path = r"C:\Users\Venkatesh\AppData\Local\Programs\Python\Python35\chromedriver.exe" 
     driver = webdriver.Chrome(chrome_path) 
     RegionIDArray = url 
     data_list=[] 
     data = [] 
     mobile_details_data = [] 
     delay = 30 # seconds 
     for reg in RegionIDArray: 
      driver.get(reg) 
driver.quit() 

錯誤:

Traceback (most recent call last): 
    File ".\input_file.py", line 24, in <module> 
    driver.get(reg) 
    File "C:\Users\Venkatesh\AppData\Local\Programs\Python\Python35\Lib\site-packages\selenium\webdriver\remote\webdriver. 
py", line 250, in get 
    self.execute(Command.GET, {'url': url}) 
    File "C:\Users\Venkatesh\AppData\Local\Programs\Python\Python35\Lib\site-packages\selenium\webdriver\remote\webdriver. 
py", line 238, in execute 
    self.error_handler.check_response(response) 
    File "C:\Users\Venkatesh\AppData\Local\Programs\Python\Python35\Lib\site-packages\selenium\webdriver\remote\errorhandl 
er.py", line 193, in check_response 
    raise exception_class(message, screen, stacktrace) 
selenium.common.exceptions.WebDriverException: Message: unknown error: unhandled inspector error: {"code":-32000,"messag 
e":"Cannot navigate to invalid URL"} 
    (Session info: chrome=57.0.2987.133) 
    (Driver info: chromedriver=2.28.455520 (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT 6.2.9200 x86_64) 

回答

2

您的url變量包含您想要訪問的鏈接。你的代碼正在循環一個字符串,並對每個字符進行一次driver.get()調用。這基本上解釋了錯誤。

因爲您已經在循環訪問for row in reader:中的數據,所以不需要內部循環。只需使用driver.get(url)即可。

+0

如果mydata.csv有兩行,它會打開兩個不同的瀏覽器。我想打開一個瀏覽器,意思是每次URL將被相同的瀏覽器取代。 –

+0

@VenkateshPanabaka - 然後在循環之前實例化Chrome驅動程序driver = webdriver.Chrome(chrome_path)。 – JRodDynamite

+1

非常感謝您幫助解決我的問題。 –

相關問題