将BeautifulSoup元素解析为Selenium

时间:2016-06-22 23:06:35

标签: python html selenium beautifulsoup

我想使用selenium获取网站的源代码;使用BeautifulSoup找到一个特定的元素;然后将其作为selenium.webdriver.remote.webelement对象解析回selenium。 像这样:

driver.get("www.google.com")
soup = BeautifulSoup(driver.source)
element = soup.find(title="Search")

element = Selenium.webelement(element)
element.click()

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:2)

对我有用的一般解决方案是计算the xpath of the bs4 element,然后使用它来查找selenium中的元素,

xpath = xpath_soup(soup_element)
selenium_element = driver.find_element_by_xpath(xpath)

...

import itertools

def xpath_soup(element):
    """
    Generate xpath of soup element
    :param element: bs4 text or node
    :return: xpath as string
    """
    components = []
    child = element if element.name else element.parent
    for parent in child.parents:
        """
        @type parent: bs4.element.Tag
        """
        previous = itertools.islice(parent.children, 0, parent.contents.index(child))
        xpath_tag = child.name
        xpath_index = sum(1 for i in previous if i.name == xpath_tag) + 1
        components.append(xpath_tag if xpath_index == 1 else '%s[%d]' % (xpath_tag, xpath_index))
        child = parent
    components.reverse()
    return '/%s' % '/'.join(components)

答案 1 :(得分:1)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup

driver = webdriver.Chrome()
driver.get("http://www.google.com")
soup = BeautifulSoup(driver.page_source, 'html.parser')
search_soup_element = soup.find(title="Search")
input_element = soup.select('input.gsfi.lst-d-f')[0]

search_box = driver.find_element(by='name', value=input_element.attrs['name'])
search_box.send_keys('Hello World!')
search_box.send_keys(Keys.RETURN)

这非常有用。我可以看到使用webdriver和BeautifulSoup的原因,但不一定适用于这个例子。

答案 2 :(得分:0)

我不知道从bs4传递到selenium的任何方法,但你可以使用selenium来找到元素:

driver.find_element_by_xpath('//input[@title="Search"]').click()

或者发现只使用像bs4这样的标题文字:

driver.find_element_by_xpath('//*[@title="Search"]').click()