javascript - 使用 Python 和 Selenium Webdriver 抓取 javascript

标签 javascript python python-2.7 selenium web-scraping

我正在尝试从 Ask 中抓取广告,这些广告是由 Google 托管的 JS 在 iframe 中生成的。

当我手动导航并查看源代码时,它们就在那里(我专门寻找 ID 为“adBlock”的 div,它位于 iframe 中)。

但是当我尝试使用 Firefox、Chromedriver 或 FirefoxPortable 时,返回给我的源代码缺少我正在查找的所有元素。

我尝试使用 urllib2 进行抓取并得到相同的结果,即使添加了必要的 header 也是如此。我确信像 Webdriver 创建的物理浏览器实例可以解决这个问题。

这是我正在使用的代码,它必须从几个不同的来源拼凑在一起:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pprint

# Create a new instance of the Firefox driver
driver = webdriver.Chrome('C:\Python27\Chromedriver\chromedriver.exe')
driver.get("http://www.ask.com")

print driver.title
inputElement = driver.find_element_by_name("q")

# type in the search
inputElement.send_keys("baseball hats")
# submit the form (although google automatically searches now without submitting)
inputElement.submit()

try:
    WebDriverWait(driver, 10).until(EC.title_contains("baseball"))
    print driver.title
    output = driver.page_source
    print(output)
finally:
    driver.quit()

我知道我在查看源代码时进行了几次不同的尝试,这不是我关心的。

对于为什么我从这个脚本中得到一个结果(广告被省略)和从它打开的浏览器中得到一个完全不同的结果(广告存在)有什么想法吗?我尝试过 Scrapy、Selenium、Urllib2 等。没有什么乐趣。

最佳答案

Selenium 只显示当前帧或 iframe 的内容。您必须使用类似的方法切换到 iframe

iframes = driver.find_elements_by_tag_name("iframe")

for iframe in iframes
    driver.switch_to_default_content()
    driver.switch_to_frame(iframe)

    output = driver.page_source
    print(output)

关于javascript - 使用 Python 和 Selenium Webdriver 抓取 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21445966/

相关文章:

python - 如何阻止 argparse 接受缩写的 "long name"标志? ( python 2.7)

javascript - 使用 Angular JS 删除 Facebook OAuth 哈希

python - 如何将数据附加到 python 2.7.11 中的文本文件?

javascript - 如何配置 StandardJS?

python - 在并发.futures.ProcessPoolExecutor map() 和 Submit() 方法中使用 numpy.fromiter 和 numpy.array 的问题

python - 检查对象是否为异常类

python - 类型化的内存 View 不允许在里面如果

python - Windows 中的信号处理

javascript - react | Items.map 不是一个函数

javascript - 无需导航即可从组件向 Angular 2 路由添加参数