2015-05-13 2 views
0

Использование Python 3 и MongoDB 2.6 и пытается вставить данные в моей коллекции, вот пример кода:MongoDB вставки Ошибка: pymongo.errors.ServerSelectionTimeoutError: соединение закрыто

from urllib.parse import urlparse 
from bs4 import BeautifulSoup 
import requests 
from pymongo import MongoClient 

urlList = ['http://....'] #bunch of URLs 
jsArray = [] 
cssArray = [] 

client = MongoClient('127.0.0.1', 28017) 
db = client.tagFinderProject # Getting the DB 
collection = db.tegFinder  # Getting the Collection 

for url in urlList: 
    parsed_uri = urlparse(url) 
    domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri) 
    r = requests.get(url) 
    data = r.text 
    soup = BeautifulSoup(data) 
    for lines in soup.find_all('script'): 
     if lines.get('src') is not None and '.js' in lines.get('src') and 'http' in lines.get('src'): 
      jsArray.append(lines.get('src')) 
     elif str(lines.get('src')).startswith('//'): 
      jsArray.append('http:' + lines.get('src')) 
     elif lines.get('src') is not None and '.js' in lines.get('src') and 'http' not in lines.get('src'): 
      jsArray.append(domain + lines.get('src')) 

for lines in soup.find_all('link'): 
    if lines.get('href') is not None and (lines.get('href')).endswith('.css') and 'http' in lines.get('href'): 
     cssArray.append(lines.get('href')) 
    elif lines.get('href') is not None and (lines.get('href')).endswith('.css') and 'http' not in lines.get('href'): 
     cssArray.append(domain + lines.get('href')) 

uniqueJS = list(set(jsArray)) 
uniqueCSS = list(set(cssArray)) 

for js in uniqueJS: 
    collection.insert('JS: ', js) 
for css in uniqueCSS: 
    collection.insert('CSS: ', css) 

Ofcourse перед запуском этого я начать свой MongoDB сервер и вот что он говорит:

2015-05-13T11:25:03.942-0500 [initandlisten] options: { net: { http: { RESTInterfaceEnabled: true, enabled: true } }, storage: { dbPath: "D:\Projects\mongoDB" } } 
2015-05-13T11:25:03.944-0500 [initandlisten] journal dir=D:\Projects\mongoDB\journal 
2015-05-13T11:25:03.944-0500 [initandlisten] recover : no journal files present, no recovery needed 
2015-05-13T11:25:04.045-0500 [initandlisten] waiting for connections on port 27017 
2015-05-13T11:25:04.045-0500 [websvr] admin web console waiting for connections on port 28017 

Я бегу приведенный выше код Python, и я получаю:

File ".../TagFinder/tagFinder.py", line 91, in <module> 
    collection.insert('JS: ', js) 
    File "C:\Python34\lib\site-packages\pymongo\collection.py", line 1924, in insert 
    with self._socket_for_writes() as sock_info: 
    File "C:\Python34\lib\contextlib.py", line 59, in __enter__ 
    return next(self.gen) 
    File "C:\Python34\lib\site-packages\pymongo\mongo_client.py", line 663, in _get_socket 
    server = self._get_topology().select_server(selector) 
    File "C:\Python34\lib\site-packages\pymongo\topology.py", line 121, in select_server 
    address)) 
    File "C:\Python34\lib\site-packages\pymongo\topology.py", line 97, in select_servers 
    self._error_message(selector)) 
pymongo.errors.ServerSelectionTimeoutError: connection closed 

Не могу найти, почему я получаю это. Я могу вставлять данные с помощью прошивки cmd, и я могу отображать ее на 127.0.0.1/tagFinderProject/tagFinder/

Может ли кто-нибудь указать мне в правильном направлении?

EDIT 1:

Если я изменю client = MongoClient('127.0.0.1', 28017) к client = MongoClient('mongodb://127.0.0.1:27017/')

я получаю:

TypeError: 'str' object does not support item assignment 

Ссылаясь на: collection.insert('JS: ', js)

ответ

1

Нашли проблему;

Чувство немого благодаря моей опечатке. имя 1) Коллекция: tegFinder но я пытаюсь получить 127.0.0.1/tagFinderProject/tagFinder/

2) MongoDB не может вставить Strings но только dict означает, что он нуждается в ключ к: значение пары. Таким образом, я изменил его:

dictJS = {'JS: ': js} 
collection.insert(dictJS) 

3) не часть решения, но я имею оставить соединение пустым:

client = MongoClient()  # Instead 'cliecnt = MongoClient(mongodb://127.0.0.1:27017, 28017') 
db = client.tagFinderProject # Getting the DB 
collection = db.tegFinder 
Смежные вопросы