【问题标题】:Scraping javascript with Python and Selenium Webdriver使用 Python 和 Selenium Webdriver 抓取 javascript
【发布时间】:2014-02-22 03:13:54
【问题描述】:

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

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

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

我尝试使用 urllib2 进行抓取并得到相同的结果,即使添加了必要的标头也是如此。我确信像 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 等。没有任何乐趣。

【问题讨论】:

    标签: javascript python python-2.7 selenium web-scraping


    【解决方案1】:

    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)
    

    【讨论】:

    • 你是个疯狂的科学家。工作就像一个魅力,谢谢。
    • 确实,你是maaad!完美运行!
    猜你喜欢
    • 2013-01-09
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 2020-01-10
    • 2018-03-02
    • 1970-01-01
    相关资源
    最近更新 更多