【发布时间】:2017-05-10 19:09:44
【问题描述】:
Windows 10 家庭版 64 位 Python 2.7(也在 3.3 中尝试过) Pycharm 社区 2006.3.1
对 Python 非常陌生,请耐心等待。
我想写一个脚本去谷歌,输入一个搜索短语,点击搜索按钮,在搜索结果中查找一个 URL(或任何字符串),如果那个页面上没有结果,点击Next 按钮并在后续页面上重复,直到找到 URL,停止并打印找到结果的页面。
老实说,我不在乎它是否只是在后台运行并给我结果。起初我试图让它随便打开浏览器,通过 Xpath 找到浏览器对象(搜索字段和搜索按钮)并执行。
您可以看到我已经安装并尝试过的模块。而且我已经尝试了几乎所有在 StackOverflow 上找到的代码示例 2 天,所以列出我尝试过的所有内容都会很冗长。
如果有人能告诉我最适合的模块以及任何其他方向,我们将不胜感激!
我为此尝试过的特定模块是 Selenim、剪贴板、MechanicalSoup、BeautifulSoup、webbrowser、urllib、enter image description hereunittest 和 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
【问题讨论】:
-
使用
requests和BeautifulSoup,在你的请求中添加headers = { 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5' },并且在所有请求之间休眠几秒钟以避免被阻塞。您不必单击按钮或任何东西,URL 定义了搜索查询和页面,例如google.com/search?q=stuff&start=10
标签: python selenium search browser