python利用selenium搜索并点击_如何通过Selenium和Python从Google搜索结果中单击随机链接...

Currently using Selenium+ Python and this code:

browser.get('http://www.google.com')

search = browser.find_element_by_name('q')

search.send_keys("how to search the internet")

search.send_keys(Keys.RETURN) # hit return after you enter search text

time.sleep(5) # sleep for 5 seconds so you can see the results

browser.execute_script("window.scrollTo(0, 873)")

time.sleep(2)

browser.find_element(By.XPATH, '(//h3)[3]/a').click()`

as my code.

What Happens: Goes to Google and types in the words and hits search. Scrolls down a bit and then it clicks the first link

What I want: I want to be able to click a random link from the search result page

How to do this?

Edit: This is what I meant when I said unnecessary:

Unnecessary 1: https://imgur.com/a/70qz89x

These are the only results I want:

This: https://imgur.com/a/eTatFV9

解决方案

As per your question to click() on a random link from google search results, as per your code trial if you invoke window.scrollTo(0, 873) and then invoke click() as in:

find_element(By.XPATH, '(//h3)[3]/a').click()`

Selenium will still try to attempt click() on the first match, which may not be your desired usecase.

Solution

Inorder to click() on a random link from google search results, you can create a List out of the search results and then generate a Random Number and invoke click() through an index as follows:

Code Block:

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.common.keys import Keys

from random import randint

options = webdriver.ChromeOptions()

options.add_argument("start-maximized")

options.add_argument('disable-infobars')

browser=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')

browser.get('http://www.google.com')

search = browser.find_element_by_name('q')

search.send_keys("selenium")

search.send_keys(Keys.RETURN)

my_search_list = WebDriverWait(browser, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//h3[@class='r']/a[not(ancestor::div[@class='xIleA'])]")))

myRandomNumber = randint(0, len(my_search_list))

print(myRandomNumber)

my_search_list[myRandomNumber].click()

Console Output:

4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值