考えでクリックし、すべてのリンクが表示されるまで、「詳細を表示し」、その後、単にリンクを収集することです。
このスクリプトでは、すべてのリンクが表示されるまで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があります。
さて、あなたは 'div'sを見つけました。あなたは' ** 'href'sを得る' a'タグを探したいでしょうか... ... –
'div'を選択しています( 'soup.find_all( 'div'、class _ =" col-xs-8 col-md-9 ")')、通常は 'href'属性を持っていません... – errata
リストには約9社しかありませんそのページに実際に興味のあるページは、サイトのどのページですか? –