2017-05-30 212 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

相关问题