LoginSignup
4
12

More than 5 years have passed since last update.

Selenium リンクを順にクリックして個別ページの要素を取得する

Last updated at Posted at 2017-06-09

一覧ページのリンクを一つづつクリックして個別ページの要素を取得する

前回はSeleniumを使って一覧ページの要素を全取得してページ送り、というのをやりました。今回は

1.一覧ページのリンクをクリック
2.個別ページを開いて要素取得
3.一覧に戻って次のリンクをクリック
4.個別ページを開いて要素取得

をやりました。

test.py
import os, re
import time
from selenium import webdriver

DRIVER_PATH = os.path.join(os.path.dirname(__file__), 'chromedriver')
browser = webdriver.Chrome(DRIVER_PATH)
url = 'https://wwwXXXX'
browser.get(url)
time.sleep(5)
for i in range(3):
    try:
        name_list = []

        path_front = '//*[@id="main"]/ul/li['
        count = 1
        path_end = ']/div[1]/a'

        for _ in range(5):
            path = path_front + str(count) + path_end
            for l in browser.find_elements_by_xpath(path):
                l.click()
                for t in browser.find_elements_by_xpath('//*[@id="main"]/div[1]/h1'):
                    name_list.append(t.text)
                    browser.back()
                    count += 1


        for name_title in zip(name_list):
            print (name_title, "\n+++++++++++++++++++++++++++++++++++++++++++++++++++")

        link_elem = browser.find_element_by_class_name('nextpostslink')
        link_elem.click()

        time.sleep(5)
    except:
        print ('not found!')

browser.close()

処理周りが全く美しくないのですが、結局のところリンクをliの何番目、というのを追加して行っている感じになりました。とはいえ、これでほぼ目的が達成できたので終了です。

4
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
12