Skip to main content
 首页 » 编程设计

python之使用 Python 遍历给定搜索短语和 URL 的 Google 搜索结果

2024年10月17日11findumars

Windows 10 家庭版 64 位 Python 2.7(也在 3.3 中尝试过) Pycharm 社区 2006.3.1

Python 的新手,请多多包涵。

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

老实说,我不在乎它是否只是在后台运行并给我结果。起初我试图让它乱七八糟地打开浏览器,通过 Xpath 找到浏览器对象(搜索字段和搜索按钮)并执行它。

您可以看到我安装和试用过的模块。我已经尝试了 2 天在 StackOverflow 上找到的几乎所有代码示例,因此列出我尝试过的所有内容会非常冗长。

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

我为此尝试过的具体模块是 Selenim、剪贴板、MechanicalSoup、BeautifulSoup、webbrowser、urllib、enter image description here单元测试和 Popen。

提前致谢! 钱茨

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 

请您参考如下方法:

Selenium 实际上是用于该脚本的一个简单/好的模块;在这种情况下你不需要任何其他东西。达到目标的最简单方法可能是这样的:

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 

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

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