如何使用Selenium,Python从Google搜索中提取链接
发布时间:2020-12-20 13:11:02 所属栏目:Python 来源:网络整理
导读:我试图让Google提取查询的相关搜索链接,在这种情况下我使用的是维基百科,然后通过Selenium解析前三个的网址.到目前为止,我只能做第一部分,谷歌搜索.这是我的代码: from selenium import webdriverfrom selenium.common.exceptions import TimeoutExceptionf
我试图让Google提取查询的相关搜索链接,在这种情况下我使用的是维基百科,然后通过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’路径所指向的链接. Here’s a picture of a Google page that I’m describing. 在这种情况下,我希望拉出链接http://en.wikipedia.com/wiki/salary 对不起文字的墙,我想尽可能具体.不管怎样,谢谢您的帮助. 最好的祝福! 解决方法
问题是这个XPath不正确 – 有一个元素在文本中有“Wikipedia”,而不是h3元素.修理它:
driver.find_element_by_xpath("//a[contains(text(),'Wikipedia')]").click() 您甚至可以使用以下方法进一步简化它: driver.find_element_by_partial_link_text("Wikipedia").click() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |