2017-05-30 12 views
-1

こんにちは私は、会社のリンクを次のウェブサイトhttps://www.unpri.org/directory/から削り取ろうとしています。しかし、私のコードはhrefの代わりにNoneを返し続けます。ここに私のコードがあります。私はここで検索しようとしましたが、同じ問題を抱えている他の人を見つけることができませんでした。ここで.get( 'href')hrefの代わりにNoneを返す

は私orignialコード

from splinter import Browser 
import bs4 as bs 
import os 
import time 
import csv 

url = 'https://www.unpri.org/directory/' 

path = os.getcwd() + "/chromedriver" 
executable_path = {'executable_path': path} 
browser = Browser('chrome', **executable_path) 

browser.visit(url) 

source = browser.html 

soup = bs.BeautifulSoup(source,'lxml') 



for url in soup.find_all('div',class_="col-xs-8 col-md-9"): 
    print(url.get('href', None)) 
+3

さて、あなたは 'div'sを見つけました。あなたは' ** 'href'sを得る' a'タグを探したいでしょうか... ... –

+2

'div'を選択しています( 'soup.find_all( 'div'、class _ =" col-xs-8 col-md-9 ")')、通常は 'href'属性を持っていません... – errata

+0

リストには約9社しかありませんそのページに実際に興味のあるページは、サイトのどのページですか? –

答えて

0

考えでクリックし、すべてのリンクが表示されるまで、「詳細を表示し」、その後、単にリンクを収集することです。

このスクリプトでは、すべてのリンクが表示されるまで3つのボタンをすべてクリックするようにSeleniumを使用しました。その後、フルページのhtmlをpage_source.htmlという名前のファイルに保存します。

htmlはBeautifulSoupで解析され、dict({org_name: url})に保存され、organisations.jsonという名前のjsonファイルにダンプされます。

import json 
from time import sleep 

from bs4 import BeautifulSoup 
from selenium import webdriver 
from selenium.common.exceptions import ElementNotVisibleException 


def click_button_until_all_displayed(browser, button_id): 
    button = browser.find_element_by_id(button_id) 
    while True: 
     try: 
      button.click() 
     except ElementNotVisibleException: 
      break 
     sleep(1.2) 


BASE_URL = 'https://www.unpri.org' 
driver = webdriver.Chrome() 
driver.get('{}/directory'.format(BASE_URL)) 

for button_name in ('asset', 'invest', 'services'): 
    click_button_until_all_displayed(driver, 'see_all_{}'.format(button_name)) 

with open('page_source.html', 'w') as f: 
    f.write(driver.page_source) 

driver.close() 

with open('page_source.html', 'r') as f: 
    soup = BeautifulSoup(f, 'lxml') 

orgs = {} 
for div in soup.find_all('div', class_="col-xs-8 col-md-9"): 
    org_name = div.h5.a.text.strip() 
    orgs[org_name] = '{}{}'.format(BASE_URL, div.h5.a['href']) 

with open('organisations.json', 'w') as f: 
    json.dump(orgs, f, indent=2) 

すべてのリンクが表示されるまでにわずか4分かかりました。時間を節約したい場合は、とorganisations.jsonというこのソースコードを示すlink to the gistがあります。

関連する問題