使用Python通过给定的搜索短语和URL浏览Google搜索结果



Windows 10 Home 64位Python 2.7(也以3.3进行了尝试)Pycharm社区2006.3.1

Python非常陌生,所以请忍受我。

我想编写一个将转到Google的脚本,输入搜索短语,单击搜索按钮,查看搜索结果,查看URL(或任何字符串),如果该页面上没有结果,请单击下一步按钮,然后在后续页面上重复直到找到URL,停止并打印结果的哪个页面。

老实说,我不在乎它是否仅在后台运行并给我结果。首先,我试图让它打开浏览器,通过XPath找到浏览器对象(搜索字段和搜索按钮),并执行为。

您可以看到我已安装和尝试的模块。我已经尝试了我在Stackoverflow上发现的几乎所有代码示例2天,因此列出我尝试过的所有内容都是很W的。

如果有人告诉我最有效的模块,那么任何其他方向都将不胜感激!

我为此尝试过的特定模块是Selenim,剪贴板,机械套件,美丽的SOUP,Webbrowser,Urllib,输入Image Description thereunittest和popen。

预先感谢您!chantz

import clipboard
import json as m_json
import mechanicalsoup
import random
import sys
import os
import mechanize
import re
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import unittest
import webbrowser
from mechanize import Browser
from bs4 import BeautifulSoup
from subprocess import Popen
######################################################
######################################################
# Xpath Google Search Box
# //*[@id="lst-ib"]
# Xpath Google Search Button
# //*[@id="tsf"]/div[2]/div[3]/center/input[1]
######################################################
######################################################
webbrowser.open('http://www.google.com')
time.sleep(3)
clipboard.copy("abc")  # now the clipboard content will be string "abc"
driver = webdriver.Firefox()
driver.get('http://www.google.com/')
driver.find_element_by_id('//*[@id="lst-ib"]')
text = clipboard.paste("abc")  # text will have the content of clipboard
print('text')
# browser = mechanize.Browser()
# url = raw_input("http://www.google.com")
# username = driver.find_element_by_xpath("//form[input/@name='username']")
# username = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")
# username = driver.find_element_by_xpath("//*[@id="lst-ib"]")
# elements = driver.find_elements_by_xpath("//*[@id="lst-ib"]")
# username = driver.find_element_by_xpath("//input[@name='username']")
# CLICK BUTTON ON PAGE
# http://stackoverflow.com/questions/27869225/python-clicking-a-button-on-a-webpage

硒实际上将是用于此脚本的简单/良好模块。在这种情况下,您不需要其他任何东西。达到目标的最简单方法可能是这样的:

from selenium import webdriver
import time
driver = webdriver.Firefox()
url = 'https://www.google.nl/'
linkList = []
driver.get(url)

string ='search phrase'
text = driver.find_element_by_xpath('//*[@id="lst-ib"]')
text.send_keys(string)
time.sleep(2)
linkBox = driver.find_element_by_xpath('//*[@id="nav"]/tbody/tr')
links = linkBox.find_elements_by_css_selector('a')
for link in links:
    linkList.append(link.get_attribute('href'))
print linkList

此代码将打开您的浏览器,输入您的搜索短语,然后获取不同页码的链接。从这里,您只需要编写一个进入浏览器中每个链接的循环,然后查看搜索短语是否存在。

我希望这会有所帮助;如果您有其他问题,请告诉我。

最新更新