2017-05-30 209 views
-1

您好,我正在嘗試從以下網站獲取公司鏈接https://www.unpri.org/directory/。然而,我的代碼不斷返回None而不是href,這裏是我的代碼。我試着在這裏尋找,但似乎無法找到其他人有同樣的問題。.get('href')返回None而不是href

這裏是我的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 ...你不想找到'a'標籤來獲取他們的**'href's嗎? –

+2

你正在選擇'div'元素('soup.find_all('div',class _ =「col-xs-8 col-md-9」)'),他們通常沒有'href'屬性... – errata

+0

只有大約9家公司在該頁面上。網站上的哪個頁面是您真正感興趣的頁面? –

回答

0

的想法是點擊「顯示更多」,直到所有的鏈接顯示,然後只需收集的鏈接。

我用Selenium編寫了這個腳本來點擊所有三個按鈕,直到顯示出所有的鏈接。然後將整頁html保存到名爲page_source.html的文件中。

然後使用BeautifulSoup解析html,保存爲字典({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分鐘。如果你想節省一些時間,這裏有一個link to the gist顯示這個源代碼,page_source.htmlorganisations.json

相關問題