如何使用Selenium Python

时间:2017-04-13 06:16:07

标签: python python-3.x selenium

这是我的代码,它只是访问第一个网址而不是所有..请让我知道如何解决..

from selenium.webdriver.firefox.firefox_profile import FirefoxProfile 
import random 
from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 

browser.get('https://www.google.co.uk/search?q=Rashmi&oq=Rashmi&aqs=chrome..69i57j69i60l3.6857j0j1&sourceid=chrome&ie=UTF-8#q=Mobiles+in+london')
time.sleep(5)

try:        
        p_links = browser.find_elements_by_css_selector(' div > h3 > a')
        url_list = []
        for urls in p_links:
            if "London" in urls.text:

                urls.get_attribute("href")
                url_list.append(urls)
                for links in url_list:
                    browser.get(links)
                    time.sleep(4)
except:
    browser.close()

1 个答案:

答案 0 :(得分:0)

这里你要将web元素添加到url_list而不是href属性值,因此当它命中行driver.get(webelement)时抛出异常

以下是修改后的代码:

from selenium import webdriver 
import time

driver = webdriver.Chrome()
driver.get('https://www.google.co.uk/search?q=Rashmi&oq=Rashmi&aqs=chrome..69i57j69i60l3.6857j0j1&sourceid=chrome&ie=UTF-8#q=Mobiles+in+london')
time.sleep(5)

try:        
        p_links = driver.find_elements_by_css_selector('div > h3 > a')
        url_list = []
        for url in p_links:
            print url.get_attribute("href")
            url_list.append(url.get_attribute("href"))
        for urls in url_list:
            if "london" in urls:
                print "Opening "+urls
                driver.get(urls)
except Exception, e:
    print str(e)
    driver.close()

driver.close() 

让我知道它是否适合你。