【发布时间】: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