2016-03-27 15 views
4

Google'dan bir sorgunun ilgili Arama Bağlantılarını açmasını isteme çalışıyorum, bu durumda Wikipedia'yı kullanıyorum ve ardından ilk üçün URL'lerini Selenium aracılığıyla ayrıştıracağım. Şimdiye kadar sadece ilk bölüm olan Googling'i yapabildim. Ben Selenyum belgelerinden örnek kullanmaya çalışıyorumSelenium, Python'u kullanarak Google Arama'dan Bağlantılar Nasıl Çekilir?

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() 

yüzden zaman zaman görüş ve, gereksiz kod mazur edin: İşte benim kod.

ben sorun yaşıyorum kod satırı:

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

Ne alakalı Vikipedi bağlantısını elde edilir yapmaya teşebbüs veya değilim, daha spesifik olarak, bağlantı olduğunu H3 'r' yol yönlendirir. Bu durumda

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

, ben metnin duvara bağlantısını http://en.wikipedia.com/wiki/salary

Maalesef çekin isteyen, ben mümkün olduğunca spesifik olmaya çalışıyorum. Her neyse, yardım için şimdiden teşekkür ederim.

Saygılarımızla!

cevap

0

Sorun şu ki bu XPath doğru değil - a öğesi, metin içinde "Vikipedi" olan h3 öğesinden değil. Fix it:

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

Hatta daha ileri gidip, kullanarak kolaylaştırabilirsiniz: tavsiye için

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

Teşekkür! –

+0

Denedim ve bir traceback hatası aldım –

+0

@HillaryDuff bu tamamlanmamış bir traceback'tir - tam izini ve hatayı kendiniz gönderebilir misiniz? – alecxe

İlgili konular