4

Python 用の Selenium API を使用して、特定の Web ページのランダムなリンクをクリックするにはどうすればよいですか。? 私はpython 2.7を使用しています。ありがとう

4

3 に答える 3

9

find_elements_by_tagname() は確実に機能します。別のオプションもあります。空の文字列を渡すことができる find_elements_by_partial_link_text を使用できます。

>>> from selenium import webdriver
>>> from random import randint

>>> driver = webdriver.Firefox()
>>> driver.get('http://www.python.org')

>>> links = driver.find_elements_by_partial_link_text('')
>>> l = links[randint(0, len(links)-1)]
>>> l.click()
于 2013-06-07T10:33:23.433 に答える
1

driver = webdriver.Firefox()
driver.get('https://www.youtube.com/watch?v=hhR3DwzV2eA')


# store the current url in a variable
current_page = driver.current_url

# create an infinite loop
while True:
    try:
        # find element using css selector
        links = driver.find_elements_by_css_selector('.content-link.spf-link.yt-uix-sessionlink.spf-link')

        # create a list and chose a random link
        l = links[randint(0, len(links) - 1)]

        # click link
        l.click()

        # check link
        new_page = driver.current_url

        # if link is the same, keep looping
        if new_page == current_page:
            continue
        else:
            # break loop if you are in a new url
            break
    except:
        continue

リストの作成は機能しますが、私のような問題が発生している場合は、タイムアウト エラーが発生し続けるか、Web ドライバーが一貫してリンクをクリックしない場合に、このコードを使用してください。

例として、YT ビデオを使用しました。右側にあるおすすめの動画をクリックするとします。これらのリンクには独自の CSS セレクターがあります。

無限ループを作りたい理由は b/c 要素のリストを作るとき、何らかの理由で python は格納された要素をうまく表現できません。タイムアウトエラーなどを取得し、ランダムリンクをクリックするように強制したい場合は、「例外」b/c をすべてキャッチしてください。

于 2017-01-29T08:15:07.400 に答える