Random IP Browsing Script / Bot with Selenium and Python

MAG WEB DESIGNS

Regular Member
Joined
Nov 18, 2017
Messages
222
Reaction score
55
Trying to post some code here. Doing some tutorials and the code tags here are not liking my comment structure keeps sayings it's spam. Really trying to give back here :)

The full code and tutorials are here .

mipython.com

trying to get this working lol

Code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

Trying to post some code here. Doing some tutorials and the code tags here are not liking my comment structure keeps sayings it's spam. Really trying to give back here :)

The full code and tutorials are here .

com

trying to get this working lol

Code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def bot1():
   url = input("WHAT URL WOULD YOU LIKE TO VISIT ANON? ") 
   print("DRIVER IS CHROME")
   driver = webdriver.Chrome()
   print("GETTING kproxy")
   driver.get("")
   elem = driver.find_element_by_id('maintextfield').clear()
   elem = driver.find_element_by_id("maintextfield").send_keys(url)
   elem = driver.find_element_by_id("maintextfield").send_keys(Keys.ENTER)
   
run = True
while run == True:
   bot1()
else:
   print("press ctrl-c to exit")

print("RUN BOT1")
bot1()

Had to take out the url for the anonimizer that makes this work due to the anti spam measures. Can I just spam 15 post in this thread so I can post links?

So you have to put in the web based anonymizer your self in the script.

I just started with python but find it usefull for automating things like logins and postings.

So my main focus has been automating web design practices, blog postings, etc..

I like using Selenium with python for automation.

there are several methods to randomize your IP for testing purposes.

The above method with a web based randomizer is one. Another is a random proxy in a list. or both!!

I've been working on web scrappers with the request and beautiful soup modules. This is the first step in a posting bot that searchs for a string finds the top 10 results, posts that string to a web based login.
 
Last edited by a moderator:
it's pretty cool. What program do you use to combine selenium with python? I am newbie for automation here, I am trying to learn, if you don't mind to show me a right direction =)
 
it's pretty cool. What program do you use to combine selenium with python? I am newbie for automation here, I am trying to learn, if you don't mind to show me a right direction =)

I just started with python too. Digging the syntax so far.
The team that made Selenium made a Python webdriver library. Just import like any other library/module. I learned a lot from reading the docs here. Seem to be fairly straight forward.

selenium-python.readthedocs.io/

I took some time off from work for the holiday. Gonna get back to automating logins here in a few :)

Happy holidays
 
Trying to post some code here. Doing some tutorials and the code tags here are not liking my comment structure keeps sayings it's spam. Really trying to give back here :)

The full code and tutorials are here .

mipython.com

trying to get this working lol

Code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

Trying to post some code here. Doing some tutorials and the code tags here are not liking my comment structure keeps sayings it's spam. Really trying to give back here :)

The full code and tutorials are here .

com

trying to get this working lol

Code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def bot1():
   url = input("WHAT URL WOULD YOU LIKE TO VISIT ANON? ")
   print("DRIVER IS CHROME")
   driver = webdriver.Chrome()
   print("GETTING kproxy")
   driver.get("")
   elem = driver.find_element_by_id('maintextfield').clear()
   elem = driver.find_element_by_id("maintextfield").send_keys(url)
   elem = driver.find_element_by_id("maintextfield").send_keys(Keys.ENTER)
  
run = True
while run == True:
   bot1()
else:
   print("press ctrl-c to exit")

print("RUN BOT1")
bot1()

Had to take out the url for the anonimizer that makes this work due to the anti spam measures. Can I just spam 15 post in this thread so I can post links?

So you have to put in the web based anonymizer your self in the script.

I just started with python but find it usefull for automating things like logins and postings.

So my main focus has been automating web design practices, blog postings, etc..

I like using Selenium with python for automation.

there are several methods to randomize your IP for testing purposes.

The above method with a web based randomizer is one. Another is a random proxy in a list. or both!!

I've been working on web scrappers with the request and beautiful soup modules. This is the first step in a posting bot that searchs for a string finds the top 10 results, posts that string to a web based login.


A couple of things to note about your code:

1. You're not validating the user's input. This is one of the first rules of coding and you broke it.
2. Usually prefer the logging module over print
3. driver.get(url) will cause selenium to fetch the url. not sure where your going with driver.get("") but it seems odd.
 
A couple of things to note about your code:

1. You're not validating the user's input. This is one of the first rules of coding and you broke it.
2. Usually prefer the logging module over print
3. driver.get(url) will cause selenium to fetch the url. not sure where your going with driver.get("") but it seems odd.

Yeah still just learning here.

I don't know how to validate the user input at this point. Input was mainly used as a place holder for a list at some point.

Again don't know about the logging module at this point. Is that unittest? I just sort of debug through the terminal with various print statements so I know where the script is(if that makes sense).

driver.get() should be url for the anonimizer kproxy. can't post links yet.

As mentioned still learning here. You're right it's good to get into a good standard of coding style.
 
Trying to post some code here. Doing some tutorials and the code tags here are not liking my comment structure keeps sayings it's spam. Really trying to give back here :)

Code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

Code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def bot1():
   url = input("WHAT URL WOULD YOU LIKE TO VISIT ANON? ")
   print("DRIVER IS CHROME")
   driver = webdriver.Chrome()
   print("GETTING kproxy")
   driver.get("")
   elem = driver.find_element_by_id('maintextfield').clear()
   elem = driver.find_element_by_id("maintextfield").send_keys(url)
   elem = driver.find_element_by_id("maintextfield").send_keys(Keys.ENTER)
 
run = True
while run == True:
   bot1()
else:
   print("press ctrl-c to exit")

print("RUN BOT1")
bot1()

this is how i will make it

Code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def bot1():
   url = input("WHAT URL WOULD YOU LIKE TO VISIT ANON? ")
   print("DRIVER IS CHROME")
   driver = useProxy(proxy)                                                       # if you want to use proxy you have to initialize chrome with it driver = webdriver.Chrome()
   print("GETTING kproxy")                                               
   driver.get(url)                                                               #go to the url that you got with the input
   driver.find_element_by_id('maintextfield').clear()
   driver.find_element_by_id("maintextfield").send_keys(url)
   driver.find_element_by_id("maintextfield").submit()                                  #submit = press enter on a form  send_keys(Keys.ENTER)
 

#method to use proxy
def useProxy(proxy):
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--proxy-server=%s' % proxy)
    chrome = webdriver.Chrome(chrome_options=chrome_options)
    return chrome

run = True
while run == True:
   bot1()
else:
   print("press ctrl-c to exit")

print("RUN BOT1")
bot1()
 
I just started with python too. Digging the syntax so far.
The team that made Selenium made a Python webdriver library. Just import like any other library/module. I learned a lot from reading the docs here. Seem to be fairly straight forward.

selenium-python.readthedocs.io/

I took some time off from work for the holiday. Gonna get back to automating logins here in a few :)

Happy holidays

Cool I will Try it! Thanks
 
So in a simple English, what does this bot do? Assume you are explaining to somebody who has basic knowledge on bots.
 
Stkr Dngr
So in a simple English, what does this bot do? Assume you are explaining to somebody who has basic knowledge on bots.

Sorry for the late response. I took some time off from IM for the holidays.

This is just a script that uses a web service to some what spoof an IP. It was my first building block in some code
so my IP wouldent get banned when I was doing educational stuff. :D

You could do the same with a proxy list or a combination of both methods.​
 
Grimasaur
this is how i will make it

I like it and here's a one up. One more piece in the puzzle. Maybe we can get to integrating everything together soon.

After the tutorial on basic(very basic) IP rotation we need something cool to do with those random IPs. One of my uses is web scrapping. Web scrapping is the collection of relevant data for later use. So today we will build ourselves a basic web scrapping script / bot ( Does it sound naive or “less intelligent” to call a scripting language script a bot? I like the term bot, yet I can see the distinction.)

Lets get to work.

We will be using Requests to grab the page source and BeautifulSoup4 to format the data to a readable state. We will then use the methods of open() and write() to save the page data to our local hard drive. Let’s go.

First our imports.

Code:
############################################################ IMPORTS
import requests
from bs4 import BeautifulSoup

The code below defines several global variables.

-The user inputed url.
-The data from the request.get method.
Code:
####### REQUESTS TO GET PAGE : BS4 TO PARSE DATA
#GLOBAL VARS
####### URL FOR SITE TO SCRAPE
url = input(“WHAT URL WOULD YOU LIKE TO SCRAPE? “)
####### REQUEST GET METHOD for URL
r = requests.get(“” + url)
####### DATA FROM REQUESTS.GET
data = r.text

Now lets turn that global var “data” into a BS4 object so we can format it with the BS4 prettify method.
Code:
####### MAKE DATA VAR BS4 OBJECT
source = BeautifulSoup(data)
####### USE BS4 PRETTIFY METHOD ON SOUP VAR NEW VAR SAUCE
pretty_source = source.prettify()

Lets see what we got in the Terminal so far.
Code:
print(source)

Should get the source in a big chunk of text first.
Then we print the source after the BS4 prettify() method
Code:
print(pretty_soup)

Should get a prettified format of the HTML source of the imputed page in the terminal at this point.

Now lets get to saving that file to our local hard drive. For this we need to first open the file in write mode.
To do this we pass the string “w” as the second argument in the open() method.
Code:
####### OPEN SOURCE IN WRITE MODE WITH “W” TO VAR LOCAL_FILE
####### MAKE A NEW FILE
local_file = open( url + “.scrapped.txt” , “w”)
####### WRITE THE VAR PRETTY_SOUP TO FILE
local_file.write(pretty_source)
####### CLOSE FILE
local_file.close()

In the above block of code we made a variable that creates and opens a file named after our url we imputed earlier with “.scrapped.txt” concatenated on. The first argument for the open method is the file name on local disc. The second argument is the permission in this case write.

We then write to the variable “local_file” with the .write method passing the “pretty_source” variable as an argument.

Lets run the code and see what happens.
We should now have the decently formatted source code from a particular website saved in our local working directory as a .txt file.

This script successfully scrapped the majority of websites although some don’t encode right with the BS4 object. Working on a fix. if there’s an error switch the argument to write to the requests “data” variable.

The final code for this project should like like this.
Code:
print(“*” * 30 )
print(“””### MI PYTHON SELENIUM RANDOM IP BROWSER BOT MK2
# 
# SCRIPT TO SCRAPE AND PARCE DATA FROM
# A USER IMPUTED URL. THEN SAVE THE PARSED
# DATA TO THE LOCAL HARD DRIVE.
“””)
print(“*” * 30 )

############################################################ IMPORTS
import requests
from bs4 import BeautifulSoup

####### REQUESTS TO GET PAGE : BS4 TO PARSE DATA
#GLOBAL VARS
####### URL FOR SITE TO SCRAPE
url = input(“WHAT URL WOULD YOU LIKE TO SCRAPE? ” )

####### REQUEST GET METHOD for URL
r = requests.get(“” + url)

####### DATA FROM REQUESTS.GET
data = r.text

####### MAKE DATA VAR BS4 OBJECT
source = BeautifulSoup(data, “html5lib”)
#ignore_encoding = BeautifulSoup(source.decode(‘utf-8′,’ignore’), “html5lib”)
####### USE BS4 PRETTIFY METHOD ON SOUP VAR NEW VAR SAUCE
pretty_source = source.prettify()

#print(source)

#print(pretty_source)

####### OPEN SOURCE IN WRITE MODE WITH “W” TO VAR LOCAL_FILE
####### MAKE A NEW FILE
local_file = open( url + “.scrapped.txt” , “w”)
####### WRITE THE VAR PRETTY_SOUP TO FILE
#local_file.write(ignore_encoding)
local_file.write(pretty_source)
####### CLOSE FILE
local_file.close()
 
Happy Holidays every one. I've been monkeying around with scrapping data. Thought I'd spread some good digital cheer with a new tutorial with Python and Selenium. Here's you guys early Christmas present. The function of this script / bot / daemon is :

Go to an anon page.
Inject search engine url.
Go to search engine.
Scrape the supplied key word list.

enjoy.

TOPIC MIPYTHON : KW KEY WORD SEARCH BOT WITH PYTHON AND SELENIUM

Hey everybody been having fun working with Selenium in Python . Now lets start putting it all together. Unfortunately some web sites don't want you're bots doing weird stuff to them. So lets incorporate our web scrapper into the Anon redirect function we created earlier. That way at least our real IP shouldn't be banned.

This is a useful tool for SEO optimization.

First lets import everything we need.

Code:
import time
import requests
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

Now instead of using functions individually by themselves. Let's make a class object as a container to organize all our functions into a more coherent data structure.

Below we define our class. Now, apparently a constructor is not called a constructor in python? For ease of my own understanding I'm just going to call the construction of a class a constructor for now. I could be way off with my terminology.

Code:
class KW_SEARCH_BOT(object):
   #   CONSTRUCTOR(?)
   def __init__(self,browser,search_engine_url,kw_list,package):
       self.browser = browser
       #   TEXT OF SCRAPE PAGE   UNUSED  UPON  INITIALIZATION
       self.package = package
       #   CLASS WIDE VAR FOR SEARCH ENGINE TO USE   UPON INITIALIZATION
       self.search_engine_url = search_engine_url
       #   CLASS WIDE VAR FOR KEY WORD LIST   UPON INITIALIZATION
       self.kw_list = kw_list
I called the class KW_SEARCH_BOT. You can call it whatever you want.
1.) We first construct the class with __init__ method.
2.) Then define the class wide variable "browser"
3.) "Package" variable is a blank list upon instantiation not used in this tutorial.
4.) Search engine is the search on we will be using to get our data
5.) Kw_list is our list of keywords.

Now we define the main function for our class.
Code:
def main(self):
 
       ################    REDIRECT THROUGH KPROXY   #####################
       print("OPEN BROWSER")
       self.browser.get("http://www.kproxy.com")
     
       #   FIND ELEMENT
       print("FIND ELEMENT BY ID MAINTEXTFIELD AND SEND SEARCH ENGINE URL")
       elem = self.browser.find_element_by_id("maintextfield").clear()
       elem = self.browser.find_element_by_id("maintextfield").send_keys(self.search_engine_url)
       elem = self.browser.find_element_by_id("maintextfield").send_keys(Keys.ENTER)
       #  WAIT 2 SECONDS
       time.sleep(2)

The above code defines the main function of our class. The object is going to redirect through Kproxy and insert the search engine url of our preferred search engine.
1.) Define the main function self as an object reference to the object.
2.) Get the webdriver.Chrome() as the browser
3.) Find and clear the element "maintextfield"
4.) Print the search engine url in the field.
5.) Hit enter key
6.) Wait 2 seconds

Next we are going to define our main loop to loop through our keyword list.
Code:
###   MAIN LOOP
       #   INJECT KEY WORD LIST
     
       #   LOOPS THROUGH KW_LIST AS KW
       for kw in self.kw_list:
           print("*" * 30)
           print(kw)
           print("*" * 30)
           print("INJECTING KEYWORD PAYLOAD")
           print("-" * 30)
           #   WAIT 3 SECONDS
           time.sleep(3)
           #   LOCATE ELEMENT AND CLEAR
           elem = self.browser.find_element_by_name("q").clear()
           #   LOCATE ELEMENT AND SEND KEYS :  KW VARIABLE
           elem = self.browser.find_element_by_name("q").send_keys(kw)
           #   PRESS ENTER
           elem = self.browser.find_element_by_name("q").send_keys(Keys.ENTER)
           #   WAIT 3 SECONDS
           time.sleep(3)

For the keyword(kw) in the keyword list(kw_list) we send that keyword to the search engine url through the anonimizer.

1.) Make the for loop.
2.) Print the key word currently being posted in the terminal.
3.)Wait 3 seconds.
4.).Locate element "q" and clear the field.
5.) Send the keyword from key word list.
6.) Press enter.
7.) Wait 3 seconds.

Next we are going to print the results of the search into the terminal
Code:
#   PRINT IN TERMINAL
           #   SEARCH RESULTS OF KEY WORD HITS
           hit_count = self.browser.find_element_by_class_name("sb_count")
           #   SEARCH RESULTS OF SNIPPET
           #snippet = self.browser.find_element_by_id("b_results")
           #   SEARCH RESULTS OF B_ALGO
           b_algo = self.browser.find_element_by_class_name("b_algo")
           #   TURN THEWEB OBJECT INTO TEXT AND ENCODE IN UTF-8
           b_algo_text = b_algo.text.encode("utf-8")
           print(b_algo_text)
           print(hit_count.text)

1.) hit_count equals the element with the hit count.
2.) b_algo equals the element with the description of the first item
3.) b_algo_text equals the web elements text encoded in utf-8
4.) Print both hit count and description web objects as text in the terminal.

Now lets save those same results to our local harddrive.
Code:
#   PRINT TO LOCAL FILE
           #   CREATE AND OPEN LOCAL FILE
           local_file = open(  "key_word_results.txt" , "a")
           #   WRITE TO LOCAL FILE KW VARIABLE
           local_file.write(",\n " + kw)
           #   WRITE TO LOCAL FILE HIT COUNT
           local_file.write(",\n " + hit_count.text)
           #   WRITE TO LOCAL FILE DESCRIPTION AS ENCODED STRING
           local_file.write(",\n " + str(b_algo.text.encode("utf-8")))
           local_file.write("\n " + "*" * 30)
           local_file.close()
1.) First we create and open the local file to edit as "key_word_results.txt","a")
2.) Write the current keyword with a line break
3.) Write the hit count with line break.
4.) Write the description as a string of text encoded in utf-8. I had problems with writing chinese characters or other encoding types. I found that this method works for this instance.
5.) Close the file until it loops through again.

Ok, almost done with our first key word scrapping; bot, script, daemon, whatever you feel like calling it. Lets define our key word list as a list variable. Next we need to Instantiate our class.
Code:
#   DEFINE KEW_WORDS LIST TO INPUT
key_words = ["search 1","search 2","search 3"]     
#   INSTANTIATE KW_POST_BOT AS bot
bot = KW_POST_BOT(webdriver.Chrome(),"http://www.bing.com",key_words,[])

Now, the list variable "key_words" has our search words in it. Put the key words you are interested in, in the list separated by a comma.
Instantiate the class object bot with Chrome as the web driver, Search engine url , key_words list , package list unused in this tutorial.

Call the main function of bot object
Code:
bot.main()

Time to run our program and see what happens. You should see a chrome browser window open up and go to the anonimzer url. Then the key words should be injected and the results saved both in terminal and locally.

Code:
print("*" * 30)
print("KW SEARCH BOT MIPython")
print("http://www.mipython.com")
print("*" * 30)

import time
import requests
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

#   DEFINE CLASS INHERIT FROM OBJECT
class KW_POST_BOT(object):
   #   CONSTRUCTOR(?)
   def __init__(self,browser,search_engine_url,kw_list,package):
       self.browser = browser
       #   TEXT OF SCRAPE PAGE   UNUSED  UPON  INITIALIZATION
       self.package = package
       #   CLASS WIDE VAR FOR SEARCH ENGINE TO USE   UPON INITIALIZATION
       self.search_engine_url = search_engine_url
       #   CLASS WIDE VAR FOR KEY WORD LIST   UPON INITIALIZATION
       self.kw_list = kw_list
     
   def main(self):
 
       ################    REDIRECT THROUGH KPROXY   #####################
       print("OPEN BROWSER")
       self.browser.get("http://www.kproxy.com")
     
       #   FIND ELEMENT
       print("FIND ELEMENT BY ID MAINTEXTFIELD AND SEND SEARCH ENGINE URL")
       elem = self.browser.find_element_by_id("maintextfield").clear()
       elem = self.browser.find_element_by_id("maintextfield").send_keys(self.search_engine_url)
       elem = self.browser.find_element_by_id("maintextfield").send_keys(Keys.ENTER)
       #  WAIT 2 SECONDS
       time.sleep(2)
       ###                        MAIN LOOP
       #   INJECT KEY WORD LIST
     
       #   LOOPS THROUGH KW_LIST AS KW
       for kw in self.kw_list:
           print("*" * 30)
           print(kw)
           print("*" * 30)
           print("INJECTING KEYWORD PAYLOAD")
           print("-" * 30)
           #   WAIT 3 SECONDS
           time.sleep(3)
           #   LOCATE ELEMENT AND CLEAR
           elem = self.browser.find_element_by_name("q").clear()
           #   LOCATE ELEMENT AND SEND KEYS :  KW VARIABLE
           elem = self.browser.find_element_by_name("q").send_keys(kw)
           #   PRESS ENTER
           elem = self.browser.find_element_by_name("q").send_keys(Keys.ENTER)
           #   WAIT 3 SECONDS
           time.sleep(3)
         
           #   PRINT IN TERMINAL
           #   SEARCH RESULTS OF KEY WORD HITS
           hit_count = self.browser.find_element_by_class_name("sb_count")
           #   SEARCH RESULTS OF SNIPPET
           #snippet = self.browser.find_element_by_id("b_results")
           #   SEARCH RESULTS OF B_ALGO
           b_algo = self.browser.find_element_by_class_name("b_algo")
           #   TURN THEWEB OBJECT INTO TEXT AND ENCODE IN UTF-8
           b_algo_text = b_algo.text.encode("utf-8")
           print(b_algo_text)
           print(hit_count.text)
         
         
         
           #   PRINT TO LOCAL FILE
           #   CREATE AND OPEN LOCAL FILE
           local_file = open( "date" + "_key_word_results.txt" , "a")
           #   WRITE TO LOCAL FILE KW VARIABLE
           local_file.write(",\n " + kw)
           #   WRITE TO LOCAL FILE HIT COUNT
           local_file.write(",\n " + hit_count.text)
           #   WRITE TO LOCAL FILE DESCRIPTION AS ENCODED STRING
           local_file.write(",\n " + str(b_algo.text.encode("utf-8")))
           local_file.write("\n " + "*" * 30)
           local_file.close()
         
         
#   DEFINE KEW_WORDS LIST TO INPUT
key_words = ["sample1","sample2","sample3"]     
#   INSTANTIATE KW_POST_BOT AS bot
bot = KW_POST_BOT(webdriver.Chrome(),"http://www.bing.com",key_words,[])



bot.main()
 
Last edited:
Code:
import time
import requests
from selenium import webdriver
#from selenium.webdriver.common.keys import Keys

print("*" * 30)
print("KW SEARCH BOT MIPython")
print("http://www.mipython.com")
print("*" * 30)


#   DEFINE CLASS INHERIT FROM OBJECT
class KW_POST_BOT(object):
    #   CONSTRUCTOR(?)
    def __init__(self, browser, search_engine_url, kw_list, package):
        self.browser = browser
        #   TEXT OF SCRAPE PAGE   UNUSED  UPON  INITIALIZATION
        self.package = package
        #   CLASS WIDE VAR FOR SEARCH ENGINE TO USE   UPON INITIALIZATION
        self.search_engine_url = search_engine_url
        #   CLASS WIDE VAR FOR KEY WORD LIST   UPON INITIALIZATION
        self.kw_list = kw_list

    def main(self):
        ################    REDIRECT THROUGH KPROXY   #####################
        print("OPEN BROWSER")
        self.browser.get("http://www.kproxy.com")

        #   FIND ELEMENT
        print("FIND ELEMENT BY ID MAINTEXTFIELD AND SEND SEARCH ENGINE URL")
        #No need for "elem = "
        #elem = self.browser.find_element_by_id("maintextfield").clear()
        #elem = self.browser.find_element_by_id("maintextfield").send_keys(self.search_engine_url)
        #elem = self.browser.find_element_by_id("maintextfield").send_keys(Keys.ENTER)


        self.browser.find_element_by_id("maintextfield").clear()
        self.browser.find_element_by_id("maintextfield").send_keys(self.search_engine_url)
        self.browser.find_element_by_id("maintextfield").submit()

        #  WAIT 2 SECONDS
        time.sleep(2)
        ###                        MAIN LOOP
        #   INJECT KEY WORD LIST

        #   LOOPS THROUGH KW_LIST AS KW
        for kw in self.kw_list:
            print("*" * 30)
            print(kw)
            print("*" * 30)
            print("INJECTING KEYWORD PAYLOAD")
            print("-" * 30)
            #   WAIT 3 SECONDS
            time.sleep(3)
            #   LOCATE ELEMENT AND CLEAR
           # elem = self.browser.find_element_by_name("q").clear()
            #   LOCATE ELEMENT AND SEND KEYS :  KW VARIABLE
            #elem = self.browser.find_element_by_name("q").send_keys(kw)
            #   PRESS ENTER
           # elem = self.browser.find_element_by_name("q").send_keys(Keys.ENTER)
            #   WAIT 3 SECONDS


            self.browser.find_element_by_name("q").clear()
            #   LOCATE ELEMENT AND SEND KEYS :  KW VARIABLE
            self.browser.find_element_by_name("q").send_keys(kw)
            #   PRESS ENTER
            self.browser.find_element_by_name("q").submit() 
            time.sleep(3)

            #   PRINT IN TERMINAL
            #   SEARCH RESULTS OF KEY WORD HITS
            hit_count = self.browser.find_element_by_class_name("sb_count")
            #   SEARCH RESULTS OF SNIPPET
            # snippet = self.browser.find_element_by_id("b_results")
            #   SEARCH RESULTS OF B_ALGO
            b_algoz = self.browser.find_elements_by_class_name("b_algo")
            pos=0
            for b_algo in b_algoz:
                pos+=1
                b_title = b_algo.find_element_by_tag_name('h2').text

                b_des = b_algo.find_element_by_class_name('b_caption').text
                print "Target Keyword => ",kw
                print "Title => ",b_title


                print "Description => ",len(b_des)
                print "Postion => ",pos
                print "="*17


            loot = {}
            loot[kw] = [x for x in self.browser.find_elements_by_class_name("b_algo")]

            for cake in loot[kw]:
                b_title = cake.find_element_by_tag_name('h2').text
                b_des = cake.find_element_by_class_name('b_caption').text
                print "Target Keyword => ",kw
                print "Title => ",b_title
                print "Description => ",len(b_des)
                print "="*17



            #   TURN THEWEB OBJECT INTO TEXT AND ENCODE IN UTF-8
            b_algo_text = b_algo.text.encode("utf-8")
            print(b_algo_text)
            print(hit_count.text)
            #   PRINT TO LOCAL FILE
            #   CREATE AND OPEN LOCAL FILE
            local_file = open("date" + "_key_word_results.txt", "a")
            #   WRITE TO LOCAL FILE KW VARIABLE
            local_file.write(",\n " + kw)
            #   WRITE TO LOCAL FILE HIT COUNT
            local_file.write(",\n " + hit_count.text)
            #   WRITE TO LOCAL FILE DESCRIPTION AS ENCODED STRING
            local_file.write(",\n " + str(b_algo.text.encode("utf-8")))
            local_file.write("\n " + "*" * 30)
            local_file.close()


# DEFINE KEW_WORDS LIST TO INPUT
key_words = ["sample1", "sample2", "sample3"]

# Perhaps use a file for KW ?
try:
    with open("keywords.txt",'r') as f:
        key_words = [x.strip() for x in f.readlines()]
except:
    print "No keywords.txt file found"

#   INSTANTIATE KW_POST_BOT AS bot
bot = KW_POST_BOT(webdriver.Chrome(), "http://www.bing.com", key_words, [])

bot.main()

Try your best to stay away from "from selenium.webdriver.common.keys import Keys"
I replaced Keys.ENTER with .submit() instead, try to use .submit() or .click() before having to use Keys
it's good practice to include exception handling in your code ^^
Hard coded time.sleep(x) isn't suggested, especially when it involves if an element exists or not.

Code:
while True:
  time.sleep(.2)
  #Does element exist yet?
    #if so run this code
    #break from loop
  #Element doesn't exist yet repeat...
 
Awesome revision, gonna implement some changes. Appreciate the feed back and help. Gonna get back to the grind soon.

mr-cat-black-hat-vector-illustration-blue-background-excellent-new-years-gift-card-merry-christmas-trend-lettering-79139260.jpg
 
Back
Top