我正在尝试从 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/