这里是简单版本的自动搜索,并点击,我们只需要输入自己想要搜索的关键词,然后就会自动打开百度搜索,并且将结果一个一个点开,并关闭,这里因为是展示,只设置了搜索第一页,下面是完整代码:
import time from selenium import webdriver guanjianci=input('请输入关键词:') browser = webdriver.Firefox() browser.get('http://www.baidu.com/') browser.implicitly_wait(2) browser.find_element_by_id('kw').send_keys(guanjianci) browser.find_element_by_id("su").click() def fanye(): search_windows = browser.current_window_handle searchPage = browser.find_element_by_id("page") # sites = browser.find_elements_by_class_name('c-container') sites = browser.find_elements_by_xpath('//div[@id="content_left"]//h3') yeshu = searchPage.find_element_by_xpath('//div[@id="page"]//strong') # urls=[] if int(yeshu.text) <= 1: for t in sites: # search_windows = browser.current_window_handle biaobiao=t.find_element_by_tag_name('a') biaobiao.click() # fwn=t.text # fwn=fwn.strip() # print(fwn) time.sleep(5) all_handles = browser.window_handles th = len(all_handles) # print(th) handle=all_handles[1] browser.switch_to.window(handle) time.sleep(2) yuanma = browser.current_url print(yuanma) # urls.append(yuanma) browser.close() # str1=yuanma # if str1.find("http://") != -1: # str = str1.strip("http://") # str = str.strip() # print(str) # else: # str = str1.strip("https://") # str = str.strip() # print(str) browser.switch_to.window(search_windows) time.sleep(5) time.sleep(5) searchPage.find_element_by_xpath("//div[@id='page']//a[last()]").click() time.sleep(5) fanye() # print(urls) if __name__ == '__main__': fanye()
需要更加精准的代码,实现更换IP,并点击目标网站的,可以搜索微信号:qimingseo
评论