以编程方式下载未出现在页面源代码中的文本

Programmatically download text that doesn't appear in the page source

我正在 Python 中编写爬虫程序。 给定一个网页,我按以下方式提取它的 Html 内容:

import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()

但某些文本组件 不会 出现在 Html 页面源中,例如 this page(重定向到索引,请访问一个日期和查看特定邮件)如果您查看页面源代码,您会看到邮件文本没有出现在源代码中,但似乎是由 JS 加载的。

如何以编程方式下载此文本?

我不是 python 专家,但诸如 urlopen 之类的任何函数只会让您获得静态 HTML,而不是执行它。您需要的是某种浏览器引擎来实际解析和执行 JavaScript。 好像在这里得到解答:

How to Parse Java-script contains[dynamic] on web-page[html] using Python?

这里最简单的选择是向负责电子邮件搜索的 URL 发出 POST 请求并解析 JSON 结果(提到 @recursive 因为他提出了这个想法第一的)。使用 requests 包的示例:

import requests

data = {
    'year': '1999',
    'month': '05',
    'day': '20',
    'locale': 'en-us'
}
response = requests.post('http://jebbushemails.com/api/email.py', data=data)

results = response.json()
for email in results['emails']:
    print email['dateCentral'], email['subject']

打印:

1999-05-20T00:48:23-05:00 Re: FW: The Reason Study of Rail Transportation in Hillsborough
1999-05-20T04:07:26-05:00 Escambia County School Board
1999-05-20T06:29:23-05:00 RE: Escambia County School Board
...
1999-05-20T22:56:16-05:00 RE: School Board
1999-05-20T22:56:19-05:00 RE: Emergency Supplemental just passed 64-36
1999-05-20T22:59:32-05:00 RE:
1999-05-20T22:59:33-05:00 RE: (no subject)

此处的另一种方法是让真正的浏览器在 selenium 浏览器自动化框架的帮助下处理页面加载的动态 javascript 部分:

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


driver = webdriver.Chrome()  # can also be, for example, webdriver.Firefox()
driver.get('http://jebbushemails.com/email/search')

# click 1999-2000
button = driver.find_element_by_xpath('//button[contains(., "1999 – 2000")]')
button.click()

# click 20
cell = driver.find_element_by_xpath('//table[@role="grid"]//span[. = "20"]')
cell.click()

# click Submit
submit = driver.find_element_by_xpath('//button[span[1]/text() = "Submit"]')
submit.click()

# wait for result to appear
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//tr[@analytics-event]")))

# get the results
for row in driver.find_elements_by_xpath('//tr[@analytics-event]'):
    date, subject = row.find_elements_by_tag_name('td')
    print date.text, subject.text

打印:

6:24:27am Fw: Support Coordination
6:26:18am Last nights meeting
6:52:16am RE: Support Coordination
7:09:54am St. Pete Times article
8:05:35am semis on the interstate
...
6:07:25pm Re: Appointment
6:18:07pm Re: Mayor Hood
8:13:05pm Re: Support Coordination

注意这里的浏览器也可以是headless,比如PhantomJS。而且,如果浏览器无法正常工作 - 您可以启动一个 虚拟显示器 ,请参阅此处的示例:

  • How do I run Selenium in Xvfb?

您可以向实际的 ajax 服务发出请求,而不是尝试使用网络界面。

例如,使用此表单数据对 http://jebbushemails.com/api/email.py 的 post 请求将产生 80kb 的易于解析的 json.

year:1999
month:05
day:20
locale:en-us