HTML标签之间的Selenium

时间:2012-10-13 12:18:43

标签: python selenium screen-scraping beautifulsoup

将Javascript创建的页面中的所有HTML传递给BeautifulSoup的最佳方法是什么?

我目前正在使用:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

from BeautifulSoup import BeautifulSoup

browser = webdriver.Firefox()
browser.get("http://www.yahoo.co.uk")
html = browser.find_elements_by_id("html")

但“html”始终是一个空列表。我做错了什么?

3 个答案:

答案 0 :(得分:4)

将来自Selenium的页面源传递给Beautiful Soup的正确方法是:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

from BeautifulSoup import BeautifulSoup

browser = webdriver.Firefox()
browser.get("http://www.yahoo.co.uk")
html_source = browser.page_source
html = BeautifulSoup(html_source)

这样,浏览器正在加载页面,提取FULL html源并将其传递给BeautifulSoup。结果可以像任何其他Beautiful Soup对象一样进行解析。

答案 1 :(得分:2)

HTML不是id。它应该是这样的:

html = browser.find_elements_by_tag_name("html")

因为html是一个标签。

您最初执行的搜索会返回ID已设置为“html”的所有元素。要返回的元素的示例:

<p id="html">Lorem ipsum</p>

该元素的id为“html”,标签名称为“p”。

答案 2 :(得分:2)

你也可以使用像

这样的东西
html_source = browser.page_source

这是一个webdriver提供函数调用,正是为了收集完整的源代码或“获取页面中的所有html”

相关问题