Как вытягивать ссылки из Google Search с помощью Selenium, Python
Я пытаюсь попросить Google вывести соответствующие поисковые ссылки запроса, в данном случае я использую Википедию, а затем проанализировать URL-адреса первых трех через Selenium. Пока мне удалось сделать только первую часть, погуглив. Вот мой код:
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()
Я пытаюсь использовать пример из документации Selenium, поэтому, пожалуйста, извините за комментарии и, иногда, ненужный код.
Строка кода, с которой у меня возникли проблемы:
driver.find_element_by_xpath("//h3[contains(text(),'Wikipedia')]").click()
То, что я пытаюсь сделать, это получите соответствующую ссылку Википедии, или, более конкретно, ссылку, на которую указывает путь H3 'r'.
Вот фотография страницы Google, которую я описываю.
В данном случае я хочу вытащить ссылку http://en.wikipedia.com/wiki/salary
Извините за стену текста, я стараюсь быть как можно более конкретным. В любом случае, спасибо за помощь заранее.
С Наилучшими Пожеланиями!
1 ответ:
Проблема в том, что этот XPath не корректен - есть элемент
a, который имеет "Википедию" внутри текста, а не элементh3. Исправьте это:driver.find_element_by_xpath("//a[contains(text(), 'Wikipedia')]").click()Вы можете даже пойти дальше и упростить его, используя:
driver.find_element_by_partial_link_text("Wikipedia").click()
Comments