Selenium2+python automation 34-get Baidu input associative words

foreword

Recently, a small partner asked Baidu how to locate the associative words below the input box after inputting. This is actually not difficult. It can be completely located with the element positioning mentioned above.

This article uses the Baidu input box to input keyword matching, and print out the associative vocabulary.

1. Positioning the input box associative words

1. First, enter a keyword in the Baidu input box, such as: blog, and then the keyword will be automatically matched below the input box.

2. At this time, you can use the firebug tool to locate the associated words. You can see that the matched words below have a common class attribute, and you can locate them all at this time.

2. Print all matching words

1. Get text information through the get_attribute() method

3. Click on one of the

1. Click on one of the associative words, such as: the second

2. Here you can add a judgment first. If you get it, click it. If you don't get it, don't click, so as not to throw an exception.

(If you want to click sequentially, you can use a for loop)

 

 

3. Reference code

# coding:utf-8
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.get("http://www.baidu.com")
time.sleep(1)
driver.find_element_by_id("kw").send_keys(u"博客")
# 获取百度输入框的
time.sleep(1)
bd = driver.find_elements_by_class_name("bdsug-overflow")
for i in bd:
    print i.get_attribute("data-key")

# Click one of them, such as: the second
if len(bd) > 1:
    bd[1].click()
    # Print the current page url
    print driver.current_url
else:
    print "No matching words were obtained"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325453125&siteId=291194637