2016-03-27 14 views
4

Googleに検索クエリの関連リンクをプルしてもらうよう依頼しようとしています。この場合はWikipediaを使っていて、最初の3つのURLをSeleniumで解析します。これまでのところ、私は最初の部分を行うことしかできませんでした。ここに私のコードは次のとおりです。Selenium、Pythonを使用してGoogle検索からリンクをプルする方法

from selenium import webdriver 
from selenium.common.exceptions import TimeoutException 
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 
from selenium.webdriver.support import expected_conditions as EC# available since 2.26.0 

query = raw_input("What do you wish to search on Wikipedia?\n") 
query = " " + query 

# Create a new instance of the Firefox driver 
driver = webdriver.Firefox() 

# go to the google home page 
driver.get("https://www.google.com/search?q=site%3Awikipedia.com&ie=utf-8&oe=utf-8") 

# the page is ajaxy so the title is originally this: 
print driver.title 

# find the element that's name attribute is q (the google search box) 
inputElement = driver.find_element_by_name("q") 

# type in the search 
inputElement.send_keys(query) 

# submit the form (although google automatically searches now without submitting) 
inputElement.submit() 

try: 
    # we have to wait for the page to refresh, the last thing that seems to be updated is the title 

    # You should see "cheese! - Google Search" 
    print driver.title 

    driver.find_element_by_xpath("//h3[contains(text(),'Wikipedia')]").click() 

finally: 
    driver.quit() 

私はコメントを言い訳して、時には、不要なコードしてください、セレンのドキュメントからの例を使用しようとしています。

私はとのトラブルを抱えているコードの行は次のとおりです。

driver.find_element_by_xpath("//h3[contains(text(),'Wikipedia')]").click() 

私がしようとしてる何より具体的に、関連するWikipediaのリンク、または、そのH3「R」のリンクを得ることですパスは、この場合

Here's a picture of a Google page that I'm describing.

、私はテキストの壁のためのhttp://en.wikipedia.com/wiki/salary

は申し訳ありませんが、リンクを引くことを望む、私はできるだけ具体的にしようとしています。とにかく、事前に助けてくれてありがとう。

よろしく!

答えて

0

問題は、このXPathが正しくないことです。h3要素ではなく、テキスト内に「Wikipedia」という要素があるa要素があります。それを修正:

driver.find_element_by_xpath("//a[contains(text(), 'Wikipedia')]").click() 

あなたも、さらに行くと、使用してそれを簡素化することができますアドバイス

driver.find_element_by_partial_link_text("Wikipedia").click() 
+0

感謝を! –

+0

私はそれを試して、トレースバックエラーが発生しました –

+0

@HillaryDuffこれは不完全なトレースバックです - 完全なトレースバックとエラー自体を投稿できますか? – alecxe

関連する問題